我有一组字符串,其中包含要转换为数据集的元素。本质上,我希望删除空白,并保留数据列。最简单的方法,也许也是唯一的方法,我知道这样做是把my.data写到外部文件,然后把这个外部文件读回R。有没有一个更有效的解决方案,不需要写和读取一个新的文件?谢谢你的建议。我更喜欢R基地。
my.data <- c(' abc -1.10 1.18 -3.41 1.21 ',
' def -1.71 0.21 -2.14 1.29 ',
' gg 2.19 2.93 -1.16 3.55 ',
' hvv4 0.00 -0.01 0.04 0.11 ')
my.data <- data.frame(my.data, stringsAsFactors=FALSE)
desired.result <- read.table(text = '
parm1 beta SE lcl ucl
abc -1.10 1.18 -3.41 1.21
def -1.71 0.21 -2.14 1.29
gg 2.19 2.93 -1.16 3.55
vv4 0.00 -0.01 -0.04 0.11
', header = TRUE, stringsAsFactors=FALSE)发布于 2013-11-03 06:40:48
为什么不直接在字符串上使用read.table?
out <- read.table(text = my.data, stringsAsFactors=FALSE,
header = FALSE, strip.white=TRUE)
str(out)
# 'data.frame': 4 obs. of 5 variables:
# $ V1: chr "abc" "def" "gg" "hvv4"
# $ V2: num -1.1 -1.71 2.19 0
# $ V3: num 1.18 0.21 2.93 -0.01
# $ V4: num -3.41 -2.14 -1.16 0.04
# $ V5: num 1.21 1.29 3.55 0.11发布于 2013-11-03 07:16:26
x=t(unique(unlist(strsplit(x=my.data,split=" ")))[-1])
cleaned=matrix(x,5,4)
t(cleaned)
[,1] [,2] [,3] [,4]
[1,] "abc" "def" "gg" "hvv4"
[2,] "-1.10" "-1.71" "2.19" "0.00"
[3,] "1.18" "0.21" "2.93" "-0.01"
[4,] "-3.41" "-2.14" "-1.16" "0.04"
[5,] "1.21" "1.29" "3.55" "0.11"
cleaned
[,1] [,2] [,3] [,4] [,5]
[1,] "abc" "-1.10" "1.18" "-3.41" "1.21"
[2,] "def" "-1.71" "0.21" "-2.14" "1.29"
[3,] "gg" "2.19" "2.93" "-1.16" "3.55"
[4,] "hvv4" "0.00" "-0.01" "0.04" "0.11"https://stackoverflow.com/questions/19750450
复制相似问题