我正在尝试以一种可以利用它的方式来构建我的情感列表。
我有一个数据框,其结构如下:
df <- data.frame("vehicle" = c("car", "plane", "bicycle", "helicopter", "train"),
"Value" = c(0.5, 0.2, 0.1, -1, -0.7),
"type" = c("toyota, mercedes, whatever", "Airbus, Boeing",
"Mountain bike", "NA", "TGV, ICE"))
我希望将“类型”的值与它们的值一起添加到“车辆”列中,以获得如下所示的数据框:
dfdesired <- data.frame("vehicle" = c("car", "toyota", "mercedes", "whatever", "plane", "Airbus",
"Boeing", "bicycle", "Mountain bike", "helicopter", "train", "TGV", "ICE"),
"Value" =c(0.5, 0.5, 0.5, 0.5, 0.2, 0.2, 0.2, 0.1, 0.1, -1, -0.7, -0.7, -0.7))
到目前为止,有人遇到过类似的问题吗?
非常感谢!
最佳答案
使用tidyr,您可以执行以下操作:
library(dplyr)
library(tidyr)
df %>% mutate (type2 = strsplit(paste0(vehicle,", ",type),", ")) %>%
unnest(type2) %>%
select(vehicle = type2, Value)
vehicle Value
1 car 0.5
2 toyota 0.5
3 mercedes 0.5
4 whatever 0.5
5 plane 0.2
6 Airbus 0.2
7 Boeing 0.2
8 bicycle 0.1
9 Mountain bike 0.1
10 helicopter -1.0
11 train -0.7
12 TGV -0.7
13 ICE -0.7
因此,首先我们将
vehicle
添加到type
字符串中,然后将字符串拆分为list
。此时,我们有一个data.frame
包含一列列表,我们使用unnest
按列表项获取一行,然后选择所需的列。关于r - 将共享相同值的两列与第三列合并,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45590336/