Home > Back-end >  How can I create a new variable equal to the last digit of a dataframe in R?
How can I create a new variable equal to the last digit of a dataframe in R?

Time:11-08

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.

CodePudding user response:

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

CodePudding user response:

A tidyverse option -

library(tidyverse)

yng1 <- data.frame(a = c(1:4))
yng2 <- data.frame(b = c(5:8))

result <- imap(mget(paste0('yng', 1:2)), 
              ~.x %>% mutate(survey = parse_number(.y)))

result

#$yng1
#  a survey
#1 1      1
#2 2      1
#3 3      1
#4 4      1

#$yng2
#  b survey
#1 5      2
#2 6      2
#3 7      2
#4 8      2

Or in base R -

list_df <- mget(paste0('yng', 1:2))
result <- Map(function(x, y) transform(x, survey = sub('yng', '', y)), 
              list_df, names(list_df))

This gives you list of dataframes, to make this change reflect in the individual dataframes you can use -

list2env(result, .GlobalEnv)
  •  Tags:  
  • r
  • Related