R data frame table set the values into columns

跟風遠走 提交于 2021-02-08 10:10:15

问题


There is a table:

class<-c("A","B", "B","C","D","D","D")
value<-c(1,3,2,5,6,2,5)
df<-cbind(class,value)

For example, the classes "B" and "C" have more than one value. I want to set every value of the class into a separate column. I would like to get the following output:

Could You please help me?

Thanks in advance, Best regards, Inna


回答1:


This might help:

First of all, make it a dataframe using data.frame()

class <- c("A","B", "B","C","D","D","D")
value <- c(1,3,2,5,6,2,5)
df <- data.frame(class,value)

# A bunch of packages that might help you.
library(tidyverse)

df %>%
    group_by(class) %>%
    mutate(new_names = paste0("value", 1:n())) %>%
    pivot_wider(names_from = new_names)

Output:

# A tibble: 4 x 4
# Groups:   class [4]
  class value1 value2 value3
  <chr>  <dbl>  <dbl>  <dbl>
1 A          1     NA     NA
2 B          3      2     NA
3 C          5     NA     NA
4 D          6      2      5

(I would not put 0 - NA is the specific solution if a value is missing)




回答2:


You can use split and rbind and fill the missing with lapply and [:

x <- split(df[,2], df[,1])
do.call("rbind", lapply(x, "[", 1:max(lengths(x))))
#  [,1] [,2] [,3]
#A "1"  NA   NA  
#B "3"  "2"  NA  
#C "5"  NA   NA  
#D "6"  "2"  "5" 


来源:https://stackoverflow.com/questions/62638084/r-data-frame-table-set-the-values-into-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!