首页 > 解决方案 > 将 data.frame 导出到 xlsx

问题描述

我正在使用如下的 data.frame

> ResultsFrame
  Country       Code                                    Description
1   Spain B.SP.03089       A random phrase describing the code info
2      UK D.UK.00035 Another random phrase describing the code info
...

这个data.frame是从一个类似的列表中获得的

> Results
1 Spain-B.SP.03089-A random phrase describing the code info
2 UK-D.UK.00035-Another random phrase describing the code info

对其他 2 个 var使用aux <- str_split(Results,"-")和等价物。Country <- unlist(aux)[seq(1,length(unlist(aux)),by=3)]如您所知,通过使用将其导出到 xlsx 很容易write.xlsx()

所以我的问题是我想将该data.frame导出到一个xlsx,第一列是国家,第二个代码,然后从那里为描述变量的每个单词提供一列。考虑到短语有不同的长度。

我尝试再次使用str_split类似的东西,但我无法获得解决方案,甚至无法迷路。

标签: rexcel

解决方案


因此,在提出建议后,我想用双 for 循环解决问题,我试图避免它,但这是最简单的方法。解决方案如下:

> Description <- unlist(aux)[seq(3,length(unlist(aux)),by=3)]
> Description2 <- str_split(Description," ")
> for (i in 1:length(Description2)){
+   for (j in 1:length(Description2[[i]])) Results[i,j+3] <- Description2[[i]][j]
+ }
> Results$Description <- NULL

最后一句只是按个人需要删除列。最后的结果是

  Country       Code    V4    V5    V6    V7    V8
1   Spain B.SP.03089 word1 word2 word3  <NA>  <NA>
2      UK D.UK.00035 word1 word2 word3 word4 word5
...

将其导出到 xlsx 可以满足我的需求。


推荐阅读