Jordan Wrong
Jordan Wrong

Reputation: 1245

Change Data In Specific Columns Using R

I would like to loop over a data frame and change the data in specific columns. I would like to do this specifically using purrr.

df = data.frame(a = rnorm(4), b = rnorm(4), c = rnorm(4))
print(df)
          a         b          c
1  0.6770575 -0.115178 -0.1521001
2  0.3291719  1.436888  0.1287069
3 -0.2183360 -1.311364 -0.2227273
4 -1.0290438  1.516289  0.8771463

#I want to change every other column. So I create a sequence.
df.seq = seq(1, ncol(df), 2)
print(df.seq)
[1] 1 3

Now I would like to loop over and change the specified columns to "data1" and "data2".

Here is my attempt.

change = c("data1", "data2")

map2_dfr(df.seq, change, ~df[,.x] = .y)

I have tried using some dplyr inside the map2.. and still no luck. I would like the outcome to look like the following.

   a         b     c
1 data1 -1.092680 data2
2 data1 -0.340103 data2
3 data1  1.183388 data2
4 data1 -1.257398 data2

Also, I must use a sequence here. My real data is every 29 columns I have to input a character string.

Upvotes: 0

Views: 63

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389325

I don't know the reason why this needs to be done in purrr specifically when the base R version is easy and simple

df[df.seq] <- as.list(change)

df
#      a          b     c
#1 data1 -0.4726404 data2
#2 data1 -1.0560956 data2
#3 data1 -0.6405799 data2
#4 data1 -0.8501395 data2

However, if it needs to be in purrr few options are

df[df.seq] <- purrr::map2(df[df.seq], change, ~replace(., TRUE, .y))

Or just

df[df.seq] <- purrr::map2(df[df.seq], change, ~.y)

which seems a convoluted way of doing it.

Upvotes: 1

Related Questions