Is there a better (e.g. vector) way to put part of a column name in a data frame row in R

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?

+3
source share
1 answer

temp_nom ( ):

# strsplit create list so you can sapply on it
sapply(strsplit(names(df),"_"), "[", 2)

# using regular expressions:
sub(".+_|[^_]+", "", names(df))

temp_nom ( )

df[nrow(df)+1,] <- as.numeric(temp_nom)

, :

df[nrow(df)+1,] <- as.numeric(sapply(strsplit(names(df),"_"), "[", 2))
# or
df[nrow(df)+1,] <- as.numeric(sub(".+_|[^_]+", "", names(df)))
+1

Source: https://habr.com/ru/post/1739986/


All Articles