Reputation: 27
I have a simple problem but being very new to R, I cannot seem to figure it out. I have a dataframe of the following structure:
V1 V2 V3 V4
STATE 0 0 1 1
Period 1 2 1 2
avg_FTE 40 35 42 35
I would like to rearrange this to the following:
STATE 0 1
Period 1 40 42
Period 2 35 35
I expect the answer is quite straightforward but for some reason this has tripped me up.
Many thanks in advance!
Upvotes: 1
Views: 58
Reputation: 8880
additional solution
library(tidiverse)
df %>%
t() %>%
as.data.frame() %>%
pivot_wider(id_cols = Period, names_from = STATE, values_from = avg_FTE)
Upvotes: 0
Reputation: 2306
library(reshape)
Input = (
'V1 V2 V3 V4
STATE 0 0 1 1
Period 1 2 1 2
avg_FTE 40 35 42 35 ')
df = read.table(textConnection(Input), header = T)
df <- as.data.frame(t(df))
t(dcast(df, STATE~Period, fill=0))
[,1] [,2]
STATE 0 1
1 40 42
2 35 35
We can fix the output a bit:
colnames(res) <- res[1,]
res <- res[-1,]
0 1
1 40 42
2 35 35
Upvotes: 1