R 数据框表将值设置为列 [英] R data frame table set the values into columns
本文介绍了R 数据框表将值设置为列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一张桌子:
class<-c("A","B", "B","C","D","D","D")
value<-c(1,3,2,5,6,2,5)
df<-cbind(class,value)
例如,类B"和C"有多个值.我想将类的每个值设置为单独的列.我想得到以下输出:
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:
你能帮我吗?
提前致谢,此致,茵娜
推荐答案
这可能会有所帮助:
首先,使用 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)
输出:
# 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
(我不会放 0
- NA
是缺少值的具体解决方案)
(I would not put 0
- NA
is the specific solution if a value is missing)
这篇关于R 数据框表将值设置为列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文