Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading