将列表转换为R中的data.frame

时间:2014-05-09 19:45:10

标签: r dataframe

示例数据:

ht <- list(c("word1","word2"),c("number1","number2"))

首先,strsplit()需要逗号,但我没有在字符串之间插入逗号。

我尝试过类似的东西;

lapply(ht, function(x) paste("",",",x) 

无论如何,所需的输出:

  Words   Numbers
1 word1   number1 
2 word2   numner2

其中WordsNumbers是列名。

编辑:这是我提出的,但在一栏中。

seplist <- lapply(splitString, function(x) paste(shQuote(x, type="cmd"), collapse=","))
unls <- data.table(unlist(seplist))
head(unls)

我怎样才能从这里进入理想的结果?

编辑2:我看起来像这样的数据:

      [[1]]
 [1] "WIELANDER, s.r.o."                       "Milochov 223  01706   Považská Bystrica"

[[2]]
 [1] "Vojenský technický ústav, a.s."          "kpt. Nálepku  03101   Liptovský Mikuláš"

[[3]]
 [1] "Property Service, s.r.o."   "Dlhá  25A  90031   Stupava"

3 个答案:

答案 0 :(得分:3)

利用R中的data.frame是原子向量列表(每列=单独的列表项)这一事实。这意味着你几乎拥有你想要的东西。

structure(as.data.frame(ht), names=c('Words', 'Numbers'))
##   Words Numbers
## 1 word1 number1
## 2 word2 number2

答案 1 :(得分:1)

> ht <- list(c("word1","word2"), c("number1","number2"))
> x <- data.frame(do.call(cbind, ht))
> names(x) <- c('Words', 'Numbers')
> x
  Words Numbers
1 word1 number1
2 word2 number2

当然,如果ht名为的列表,这将更加简单。

> ht <- list(Words = c("word1","word2"), Numbers = c("number1","number2"))
> data.frame(do.call(cbind, ht))
  Words Numbers
1 word1 number1
2 word2 number2

答案 2 :(得分:0)

使用lapplydo.callunlist

df<-do.call(cbind,lapply(ht,function(x) data.frame(x=unlist(x),stringsAsFactors=FALSE)))
names(df)<-c("Words","Numbers")
> df
  Words Numbers
1 word1 number1
2 word2 number2