r - 塑造数据并影响 R 中的计数列

标签 r dplyr reshape

我有这样的数据:

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/

相关文章:

用 "1"替换下一个值

r - tibble::add_row 到嵌套 tibble 在 tidyr 1.0.0 下抛出错误

r - 为 dplyr 中的每个函数保存 na.rm=TRUE

r - 在 R 中部分转置数据帧

r - 解构矩阵/重新排列矩阵列

r - R 中缺失数据的某些模式

r - 在 Debian 服务器 (linux-gnu) 上将 R 版本 2.15.1 升级到 3.3

r - R和Stata的合并命令比较

r - 索引 grouped_df 对象

matlab - 从 3D 矩阵变量切片时将 2D 矩阵展平为 1D 的最佳方法