我有这样的数据:
df<-structure(list(concept = c("agree", "anger", "anxiety", "cognitive",
"cognitive"), count = c(1L, 2L, 4L, 6L, 122L)), class = "data.frame", row.names = c(NA,
-5L))
我需要为“概念”列的每个值创建新列,以获取“计数”列中的数字,并且所需数据为:
new_df<-structure(list(agree = c(1L, 0L, 0L, 0L, 0L), anger = c(0L, 2L,
0L, 0L, 0L), anxiety = c(0L, 0L, 4L, 0L, 0L), cognitive = c(0L,
0L, 0L, 6L, 122L)), class = "data.frame", row.names = c(NA, -5L
))
agree anger anxiety cognitive
1 1 0 0 0
2 0 2 0 0
3 0 0 4 0
4 0 0 0 6
5 0 0 0 122
最佳答案
我们可以使用pivot_wider
library(dplyr)
library(tidyr)
df %>%
mutate(rn = row_number()) %>%
pivot_wider(names_from = concept, values_from =count,
values_fill = 0) %>%
select(-rn)
-输出
# A tibble: 5 × 4
agree anger anxiety cognitive
<int> <int> <int> <int>
1 1 0 0 0
2 0 2 0 0
3 0 0 4 0
4 0 0 0 6
5 0 0 0 122
或者使用base R
中的xtabs
xtabs(count ~ rn + concept, transform(df, rn = seq_along(concept)))
concept
rn agree anger anxiety cognitive
1 1 0 0 0
2 0 2 0 0
3 0 0 4 0
4 0 0 0 6
5 0 0 0 122
关于r - 塑造数据并影响 R 中的计数列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73736030/