我有一个类似于这样的框架,其中A到C事件(为简单起见缩短了,但实际上有更多的列)具有值“0-3”、“3-6”或“6-9”。
df <- data.frame(id = c(1,2,3,4,5,6,7,8,9,10),
A = c("0-3","3-6","6-9","0-3","6-9","6-9","0-3","0-3","3-6","3-6"),
B = c("9-12","3-6","0-3","3-6","0-3","0-3","3-6","6-9","6-9","3-6"),
C = c("3-6","6-9","3-6","6-9","3-6","6-9","6-9","3-6","0-3","6-9"))
df
如果我想创建一个包含事件和值的新列,以及一个1或0的布尔标志,那么什么是有效的方法呢?下面是我想要的一个例子(缩短,我希望列扩展到C_5_9)。
df <- data.frame(id = c(1,2,3,4,5,6,7,8,9,10),
A = c("0-3","3-6","6-9","0-3","6-9","6-9","0-3","0-3","3-6","3-6"),
B = c("9-12","3-6","0-3","3-6","0-3","0-3","3-6","6-9","6-9","3-6"),
C = c("3-6","6-9","3-6","6-9","3-6","6-9","6-9","3-6","0-3","6-9"),
A_0_3 = c(1,0,0,1,0,0,1,1,0,0),
A_3_6 = c(0,1,0,0,0,0,0,0,1,1),
A_6_9 = c(0,0,1,0,1,1,0,0,0,0),
B_0_3 = c(0,0,1,0,1,1,0,0,0,0),
B_3_6 = c(0,1,0,1,0,0,1,0,0,1))
df
3条答案
按热度按时间wwwo4jvm1#
也许你可以从
data.table
包中尝试dcast
+melt
你将获得
9rbhqvlz2#
以下是一个tidyverse解决方案,灵感来自@ pixasIsCoding,使用
pivot_longer
和pivot_wider
:输出量:
7gyucuyw3#
使用
match
和tabulate
。