Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

I am having the following list of data frames:

df1 <- data.frame(a = rnorm(10), b = rnorm(10), vector = 1)

df2 <- data.frame(a = rnorm(10), b = rnorm(10), vector = 2)

df3 <- data.frame(a = rnorm(10), b = rnorm(10), vector = 3)

df4 <- data.frame(a = rnorm(10), b = rnorm(10), vector = 4)

ls_df <- list(df1, df2, df3, df4)

And, I also have another list of arrays.

a1 <- rep(1, 10)

a2 <- rep(2, 10)

a3 <- rep(3, 10)

a4 <- rep(4, 10)

ls_a <- list(a1, a2, a3, a4)

I want to rearrange the columns in each data frame in ls_df such that ls_df[[1]]$a contains 1's, lf_df[[2]]$a contains 2's, and so on.

I tried the following, but this is not working:

ls_df <- lapply(ls_df["a"], function(x) ls_a)

1 Answer

0 votes
by (107k points)

For that you can use Map() in R programming:

ls_df <- Map(function(x, y) {x$a <- y;x}, ls_df, ls_a)

The same can be done with map2 from purrr:

purrr::map2(ls_df, ls_a, ~{.x$a <- .y;.x})

You probably mean a1 to a4 of length 10 and not 20 since number of rows in ls_df are 10.

a1 <- rep(1, 10)

a2 <- rep(2, 10)

a3 <- rep(3, 10)

a4 <- rep(4, 10)

ls_a <- list(a1, a2, a3, a4)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...