简体   繁体   中英

How to use cast in reshape package in r

Hi I have a data frame like this:

df <- data.frame(site = c('A','A','B','B','C','A','A'),
             state = c('O','F','O','F','O','O','F'),
             value = c(5,4,6,7,2,8,9))

It looks like this

> df

site state value
   A     O     5
   A     F     4
   B     O     6
   B     F     7
   C     O     2
   A     O     8
   A     F     9

My target output should be

site  F O
   A  4 5
   B  7 6
   C NA 2
   A  9 8

Anyone know how to achieve this?

I think there should be something related to reshape2 in R

Thanks in advance

Try:

df$id <- with(df, ave(1:nrow(df), site, state, FUN=seq_along))
library(reshape2)
dcast(df, site+id~state, value.var="value")[,-2]
#  site  F O
#1    A  4 5
#2    A  9 8
#3    B  7 6
#4    C NA 2

Or

library(tidyr)
library(dplyr)
df %>%
spread(state, value) %>%
arrange(id) %>% 
select(-id)
#  site  F O
#1    A  4 5
#2    B  7 6
#3    C NA 2
#4    A  9 8

Or

reshape(df,  idvar=c("site", "id"), timevar="state",direction="wide")[,-2]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM