How can I create a new variable equal to the last digit of a dataframe in R?

I have 2 data frames yng1 yng2. I wish to add a variable called survey to each data frame that is equal to the last digit of the data frame. The desired code should generate a variable survey with all values equal to 1 in yng1, all values equal to 2 in yng2, and so on.

I have attempted using for-loops without much success.

Example data

yng1 <- as.data.frame(c(1:4))
yng2 <- as.data.frame(c(5:8))

Desired output

> yng1
  c(1:4) survey
1      1      1
2      2      1
3      3      1
4      4      1

> yng2
  c(5:8) survey
1      5      2
2      6      2
3      7      2
4      8      2

In practice, I have many more than 2 data frames, and so I’d like to be able to loop through 1 to N to apply a function to each of the data frames. The data frames can be stored in a list if that helps.

>Solution :

You can try using this function.

surrvey <- function(df){
  df$survey <- stringr::str_sub(deparse(substitute(df)), -1)
  df
}
yng1 <- surrvey(yng1)
yng1

  c(1:4) survey
1      1      1
2      2      1
3      3      1
4      4      1

I cannot know how you want to loop and how those tables are stored. Please let me know if there is any problems.

I think stored in list is most simple.

ynglst <- list(yng1, yng2)
for(i in 1:2){
  ynglst[[i]]$survey <- i
}
ynglst

[[1]]
  c(1:4) survey
1      1      1
2      2      1
3      3      1
4      4      1

[[2]]
  c(5:8) survey
1      5      2
2      6      2
3      7      2
4      8      2

Leave a Reply