简体   繁体   English

R 数据转换:根据不同列中的数字创建新行

[英]R data transformation: create new rows based on numbers in different columns

I am searching for a solution how to transform the following data frame using dplyr:我正在寻找如何使用 dplyr 转换以下数据框的解决方案:

item <- c('A','B','C')
one <- c(2, 1, 2)
two <- c(1,1,2)
data <- data.frame(item,one,two)
data
item物品 one two
A一种 2 2 1 1
B 1 1 1 1
C C 2 2 2 2

Now, the column "one" contains the number of ratings of the value 1, the column "two" the number of ratings of the value 2. My ideal data frame after transformation would look like this:现在,列“一”包含值 1 的评级数,列“二”包含值 2 的评级数。转换后我的理想数据框如下所示:

item物品 rating评分
A一种 1 1
A一种 1 1
A一种 2 2
B 1 1
B 2 2
C C 1 1
C C 1 1
C C 2 2
C C 2 2

Any idea how I could get to this output (it doesn't have to be dplyr)?知道如何获得此输出(不必是 dplyr)吗? I know how to use pivot_longer of the tidyr package but that doesn't solve the problem of repeating the number of rows...我知道如何使用 tidyr 包的 pivot_longer 但这并不能解决重复行数的问题......

library(dplyr)
library(tidyr) # pivot_longer
nums <- c(one = 1, two = 2, three = 3)
data %>%
  pivot_longer(-item) %>%
  group_by(item) %>%
  summarize(rating = rep(name, times = value)) %>%
  ungroup() %>%
  mutate(rating = nums[rating])
# # A tibble: 9 x 2
#   item  rating
#   <chr>  <dbl>
# 1 A          1
# 2 A          1
# 3 A          2
# 4 B          1
# 5 B          2
# 6 C          1
# 7 C          1
# 8 C          2
# 9 C          2

I had to define nums because I couldn't find (in my haste) an easy way to convert "one" to 1 in a programmatic way.我必须定义nums因为我找不到(在我匆忙中)以编程方式将"one"转换为1的简单方法。 You'll need to make sure it goes out at least as far as you need;你需要确保它至少在你需要的范围内熄灭; I added three=3 for demonstration, if you truly only have one and two then you should be good as-is.我加了three=3来演示,如果你真的只有onetwo那么你应该保持原样。

(Related to that topic: Convert written number to number in R ) (与该主题相关:将书写的数字转换为 R 中的数字

也许您可以使用gather()函数将其从宽格式转换为长格式,然后将“一”和“二”的字符串值替换为整数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM