我想将一列字符串(例如 [1, 58, 10] )分隔成使用与 tidyr 分开的列。我的问题是有时列更短(永远不会更长)。我在同一个数据框中有很多关于这个问题的列。
加载包
require(tidyr)
require(dplyr)
require(stringr)
数据
在这里,我使用来自真实数据的样本制作了一个数据框。“向量”在 col1 中的长度为 10,在 col2 中的长度为 9 或 10。有一个时间列只是为了表明还有其他列。
df <- data.frame(
time = as.POSIXct(1:5, origin=Sys.time()),
col1 = c("[0,355,0,0,0,1227,0,0,382059,116]", "[0,31,0,0,0,5,0,0,925,1]", "[0,1,0,0,0,471,0,0,130339,3946]", "[0,0,0,0,0,223,0,0,37666,12]", "[0,19,0,0,0,667,0,0,336956,53]"),
col2 = c("[0,355,0,0,0,1227,0,0,382059,116]", "[0,355,0,0,0,1227,0,0,382059,116]", "[0,0,0,0,0,223,0,0,37666,12]", "[0,19,0,0,0,667,0,0,336956]","[0,355,0,0,0,1227,0,0,382059,116]")
)
我希望它如何
对于所有“向量”长度相等的第一列,我可以使用 separate() 来获得我想要的。
a1 <- df %>%
mutate(col1 = str_sub(col1,2,-2)) %>%
separate(col1, paste("col1",1:10,sep="."),",")
# Making sure the numbers are numeric
a1 <- as.data.frame(sapply(a1, as.numeric)) %>%
mutate(time = as.POSIXct(time, origin="1970-01-01")) %>% select(-col2)
这导致
> a1
time col1.1 col1.2 col1.3 col1.4 col1.5 col1.6 col1.7 col1.8
1 2014-11-07 12:21:45 0 355 0 0 0 1227 0 0
2 2014-11-07 12:21:46 0 31 0 0 0 5 0 0
3 2014-11-07 12:21:47 0 1 0 0 0 471 0 0
4 2014-11-07 12:21:48 0 0 0 0 0 223 0 0
5 2014-11-07 12:21:49 0 19 0 0 0 667 0 0
col1.9 col1.10
1 382059 116
2 925 1
3 130339 3946
4 37666 12
5 336956 53
这不适用于 col2 元素不能分成几列的地方
解决方法
# Does not work
#b1 <- df %>%
# mutate(col2 = str_sub(col1,2,-2)) %>%
# separate(col2, paste("col2",1:10,sep="."),",")
b2 <- sapply(as.data.frame(str_split_fixed(str_sub(df$col2,2,-2),',',n=10), stringsAsFactors=F), as.numeric)
colnames(b2) <- paste("col2",1:10,sep=".")
b2 <- as.data.frame(cbind(time=df$time, b2)) %>%
mutate(time = as.POSIXct(time, origin="1970-01-01"))
这导致
> b2
time col2.1 col2.2 col2.3 col2.4 col2.5 col2.6 col2.7 col2.8
1 2014-11-07 12:21:45 0 355 0 0 0 1227 0 0
2 2014-11-07 12:21:46 0 355 0 0 0 1227 0 0
3 2014-11-07 12:21:47 0 0 0 0 0 223 0 0
4 2014-11-07 12:21:48 0 19 0 0 0 667 0 0
5 2014-11-07 12:21:49 0 355 0 0 0 1227 0 0
col2.9 col2.10
1 382059 116
2 382059 116
3 37666 12
4 336956 NA
5 382059 116
如果向量较短,则最后一个元素应为 NA,因此这是正确的。
问题
有没有办法使用单独的(或其他更简单的功能)而不是解决方法?有没有办法同时将其应用于 col1 和 col2(例如,通过选择以 col 开头的列)?
谢谢!