Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert some rows to columns in dataframe in R w/o spread

I have a following dummy data frame:

group <- c(rep("cat", 3),rep("dog", 3))
time <- c(rep(1:3,2))
mean <- c(78, 81, 83, 76, 83, 85)
  
df1 <- data.frame(group, time, mean)

And I would like to convert it to the following:

cat <- c(78, 81, 83)
dog <- c(76, 83, 85)
time <- c(1:3)

df2 <- data.frame(cat, dog, time)

I can do it in following way:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df2 <- df1%>% spread(group, mean)

How can I achieve this without using spread from tidyr?

>Solution :

You can use xtabs:

df1$group <- factor(df1$group)    
xtabs(mean ~ time + group, df1)

# time cat dog
# 1  78  76
# 2  81  83
# 3  83  85
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading