3

List of dfs:

catbehave <- c("Good", "Cute", "Evil")
catnum <- c(1, 2, 3)
dogbehave <- c("Goodboi", "Cute")
dognum <- c(4, 2)
mousebehave <- c("Evil", "Good", "Cute")
mousenum <- c(3, 1, 2)

cat <- as.data.frame(cbind(catbehave, catnum))
dog <- as.data.frame(cbind(dogbehave, dognum))
mouse <- as.data.frame(cbind(mousebehave, mousenum))


list.1 <- list(cat = cat,dog = dog,mouse = mouse)

df1:

cat <- c("Good", "Evil", "Evil", "Cute")
dog <- c("Goodboi", "Goodboi", "Cute", "Goodboi")
mouse<- c("Evil", "Good", "Cute", "Evil")
df1 = data.frame(cat, dog, mouse)

I want to evaluate a list of dfs to change values in df1. Need to use name of df's in list.1 for columns in df1

Output:

df1

cat  dog  mouse
1    4    3
3    4    1
3    2    2
2    4    3

3 Answers 3

2

A base R option, assuming list.1 and df1 have the some order:

df1[] <- mapply(
  function(x, y) x[y],
  lapply(list.1, function(x) setNames(x[[2]], x[[1]])),
  df1
)
df1

#   cat dog mouse
# 1   1   4     3
# 2   3   4     1
# 3   3   2     2
# 4   2   4     3
Sign up to request clarification or add additional context in comments.

Comments

1

You can use match for the update join.

for(i in names(df1)) {
   df1[,i] <- list.1[[i]][match(df1[,i], list.1[[i]][,1]), 2]
}
df1
#  cat dog mouse
#1   1   4     3
#2   3   4     1
#3   3   2     2
#4   2   4     3

Comments

1

Using tidyverse we can do this with

library(dplyr)
library(tibble)
library(purrr)
map2_dfc(df1, list.1, ~ deframe(.y)[.x])
# A tibble: 4 x 3
#  cat   dog   mouse
#  <chr> <chr> <chr>
#1 1     4     3    
#2 3     4     1    
#3 3     2     2    
#4 2     4     3    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.