Is there a better (i.e vectorised) way to put part of a column name into a row of a data frame in R
Posted
by PaulHurleyuk
on Stack Overflow
See other posts from Stack Overflow
or by PaulHurleyuk
Published on 2010-04-06T12:37:54Z
Indexed on
2010/04/06
12:43 UTC
Read the original article
Hit count: 309
I have a data frame in R that has come about from running some stats on the result fo a melt/cast operation. I want to add a row into this dataframe containing a Nominal value. That Nominal Value is present in the names for each column
df<-as.data.frame(cbind(x=c(1,2,3,4,5),`Var A_100`=c(5,4,3,2,1),`Var B_5`=c(9,8,7,6,5)))
> df
x Var A_100 Var B_5
1 1 5 9
2 2 4 8
3 3 3 7
4 4 2 6
5 5 1 5
So, I want to create a new row, that contains '100' in the column Var A_100 and '5' in Var B_5. Currently this is what I'm doing but I'm sure there must be a better, vectorised way to do this.
temp_nom<-NULL
for (l in 1:length(names(df))){
temp_nom[l]<-strsplit(names(df),"_")[[l]][2]
}
temp_nom
[1] NA "100" "5"
df[6,]<-temp_nom
> df
x Var A_100 Var B_5
1 1 5 9
2 2 4 8
3 3 3 7
4 4 2 6
5 5 1 5
6 <NA> 100 5
rm(temp_nom)
Typically I'd have 16-24 columns. Any ideas ?
© Stack Overflow or respective owner