Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

tidyr - Transforming columns of unequal arrays to column of single values in R

As a next step after this previous question, assume that there are multiple columns of arrays that do not have the same length. For example:

Col_A Col_B Col_C
[0.1,0.5,0.7] [1.54E12, 1.54E12, 1.54E12] [1, 3, 4, 5}
question from:https://stackoverflow.com/questions/66049955/transforming-columns-of-unequal-arrays-to-column-of-single-values-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

We could use cSplit from splitstackshape

library(splitstackshape)
library(data.table)
cSplit(setDT(df)[, lapply(.SD, gsub, pattern = "[][}]", 
    replacement = "")], names(df), sep=",", fixed = FALSE, "long")
#   Col_A    Col_B Col_C
#1:   0.1 1.54e+12     1
#2:   0.5 1.54e+12     3
#3:   0.7 1.54e+12     4
#4:    NA       NA     5

data

df <- structure(list(Col_A = "[0.1,0.5,0.7]", Col_B = "[1.54E12, 1.54E12, 1.54E12]", 
    Col_C = "[1, 3, 4, 5}"), class = "data.frame", row.names = c(NA, 
-1L))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...