大家好,感谢您阅读我的问题。
我在R中具有以下内容:
**type, status, count**
human, living, 36
human, living, 57
human, dead, 43
mouse, living, 4
mouse, dead 8
我要做的是基于“类型”合并行(因此“类型”将是排他的),然后将“状态”和“计数”的内容移至合并的行并添加一些符号,如下所示:
**type, status, count**
human, living = "36, 57", dead = "43"
mouse, living = "4", dead = "8"
我确实设法合并了R(某种)中的行,但我无法弄清楚如何将状态移动并计数到合并的行并按所示进行布局。
我不必使用R,但我认为R是执行此操作的最合适方法,但我可以使用任何方法来完成工作。任何帮助将不胜感激。
非常感谢。
编辑:这是行之有效的最终解决方案(多亏了gersht):
rm(list=ls());
library(tidyr)
library(dplyr)
df <- read.table("D:/test.csv", header = TRUE, sep=",")
df <- df %>%
group_by(type, status) %>%
mutate(count = paste(count, collapse = ", ")) %>%
ungroup() %>%
distinct() %>%
spread(status, count) %>%
mutate(dead = paste("dead = ", dead),
living = paste("living = ", living))
write.table(df, col.names = FALSE)
答案 0 :(得分:1)
这将或多或少返回具有正确值的数据帧。您可以根据需要更改列顺序和列名称:
library(tidyr)
library(dplyr)
df %>%
group_by(type, status) %>%
mutate(count = paste(count, collapse = ", ")) %>%
ungroup() %>%
distinct() %>%
spread(status, count) %>%
mutate(dead = paste("dead = ", dead),
living = paste("living = ", living))
#### OUTPUT ####
# A tibble: 2 x 3
type dead living
<chr> <chr> <chr>
1 human dead = 43 living = 36, 57
2 mouse dead = 8 living = 4
我仅按type
和status
进行了分组,因此可以使用count
将mutate()
的值折叠为单个字符串。我将ungroup()
用作一种很好的做法,但这并不是绝对必要的。
这会创建一些重复项,并用distinct()
将其删除。然后,我使用spread()
函数将living
和dead
移动到它们自己的列,然后再次使用mutate
添加字符串"living = "
和{{1 }}到各自的列。
"dead = "