I have a data frame in R, which arose due to the launch of some statistics from the results of the melt / cast operation. I want to add a line to this framework containing a nominal value. This 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 containing “100” in Var A_100 column and “5” in Var B_5. This is currently what I'm doing, but I'm sure there must be a better, vector way for 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)
Normally I would have 16-24 columns. Any ideas?
source
share