[英]Column Names Across Multiple Rows?
I'm importing a csv file that consists of a crosstab with column names in a two-row hierarchy.我正在导入一个 csv 文件,该文件由一个交叉表组成,该交叉表在两行层次结构中具有列名。 When I get the table in R, the result looks like this:
当我得到R中的表时,结果是这样的:
alpha X.1 X.2 beta X.1 X.2 X.3 gamma X.1
var1 var2 var3 var1 var2 var3 var4 var1 var4
1 21 50 5 22 48 6 8 25 8
2 27 50 5 24 48 6 8 33 8
3 26 50 5 28 48 6 8 33 8
4 25 50 5 28 48 6 8 20 8
Here, alpha, beta
, and gamma
are all one level of the hierarchy, while var1
, var2
, var3
, and var4
are the second level.在这里,alpha、
beta
和gamma
都是层次结构的一级,而var1
、 var2
、 var3
和var4
是第二级。
What I would like it do is get output like the following, where the row names are concatenated but also keeping in mind the structure of the data.我希望它做的是像下面这样获取 output,其中行名称被连接起来,但也牢记数据的结构。
alpha_var1 alpha_var2 alpha_var3 beta_var1 beta_var2 beta_var3 beta_var4 gamma_var1 gamma_var4
1 21 50 5 22 48 6 8 25 8
2 27 50 5 24 48 6 8 33 8
3 26 50 5 28 48 6 8 33 8
4 25 50 5 28 48 6 8 20 8
Any ideas here?这里有什么想法吗? Haven't been able to find anything to deal with this issue.
一直没能找到任何东西来处理这个问题。 Thanks in advance.
提前致谢。
This seems to work, though the use of xts
seems a bit heavy handed for the na.locf()
function, but I know it works and use it frequently, so that's what I used.这似乎有效,尽管
xts
的使用对于na.locf()
function 来说似乎有点繁重,但我知道它有效并且经常使用它,所以这就是我使用的。
library(xts)
#Read in data without headers
x <- read.delim("Book1.txt", skip = 2, header = FALSE)
#Read in header files transposing them into columns
headers <- data.frame(t(read.delim("Book1.txt", nrows = 2, header = FALSE)), stringsAsFactors = FALSE)
#Create a now column with the value of alpha, beta, gama or NA
headers$vals <- with(headers, ifelse(grepl("[abg]", X1), X1, NA))
#Fill down the values above
headers$vals <- na.locf(headers$vals)
#Paste column names together
colnames(x) <- with(headers, paste(vals, X2, sep = "_"))
#Resulting object
x
alpha_var1 alpha_var2 alpha_var3 beta_var1 beta_var2 beta_var3 beta_var4 gamma_ var1 gamma_var4
1 21 50 5 22 48 6 8 25 8
2 27 50 5 24 48 6 8 33 8
3 26 50 5 28 48 6 8 33 8
4 25 50 5 28 48 6 8 20 8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.