I am using R, trying to change the variables in my dataframe as follows:
Age1 | Age2 | |
---|---|---|
10y | 20y | |
13y | 24y |
↓
Age1 | Age2 | |
---|---|---|
10 | 20 | |
13 | 24 |
Since these variable names are labeled as Age1, Age2, Age3... I want to use the for-loop function to change them all at once.
I tried the following code but it did not work:
df_new <- df %>%
mutate(
for (i in 1:6){
paste("Age", i, sep = "") = str_remove(paste("df$Age", i, sep = ""), "y")
}
)
Could you please tell me which part is wrong with this code? Any alternative solutions?
I would go for an alternative solution
df<-cbind("age1"=c("10y","13y"),"age2"=c("10y","13y")) %>% as.data.frame()
gsub("y","",df$age1)