简体   繁体   English

R数组置换命名列和行

[英]R array permutation naming columns and rows

This is a follow up question to convert 4-dimensional array to 2-dimensional data set in R which was answered by @Ben-Bolker. 这是将R中的4维数组转换为2维数据集的后续问题,@ Ben-Bolker 回答了这一问题

I have a 3D array called 'y' with dimensions [37,29,2635] (ie firms, years, class). 我有一个名为[y]的3D数组,其尺寸为[37,29,2635](即商号,年份,类别)。 Using Ben's formula: 使用本的公式:

avm11<-matrix(aperm(y,c(1,3,2)),prod(dim(y)[c(1,3)]))

I managed to convert it to a 2D array with dimensions [37*2635,29]. 我设法将其转换为尺寸为[37 * 2635,29]的2D数组。 However, the row names have become meaningless numbers and I'd need to generate row names during the permutation so that I'd get 97495 unique row names of the type firm_class. 但是,行名已变成无意义的数字,我需要在排列过程中生成行名,以便获得97495类型的firm_class唯一行名。

I've been trying to do so via paste0() but I'm doing something wrong. 我一直在尝试通过paste0()这样做,但是我做错了什么。 Any suggestions? 有什么建议么?

You could use seq_len() for this. 您可以seq_len()使用seq_len() Eg 例如

rownames(avm11)<-paste(seq_len(length(avm11[,1])),"observation",sep=" ")

To make the rownames dependable on the variable firm_class: 使行名依赖于firm_class变量:

#Create data frame:
df<-data.frame(X=c(0,1,2,3,4,5),Y=c("a","b","c","d","e","f"))
n<-length(df[,1])

#Generate names containing class name and unique number:
namevector<-sapply(seq_len(n),function(i) names_vector[i]<-paste("Class", df[i,1], i,sep="."))

#Equate rownames to generated names:
rownames(df)<-namevector

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM