Including columns in a dataframe in R using a rule

Asked

Viewed 93 times

4

This is my dataframe:

df<-as.data.frame(matrix(rexp(200, rate=.1), ncol=10))
colnames(df)<-c("one","two","three","four","five","six","seven","eight","nine","ten")

This is the entry I will use as an example:

index<-c(1,2,3,4,5,6,7,8,9,10)

My idea is to create columns and fill the values -2, -1, 0, 1 or 2 in these columns created according to a rule.

That would be: I will create a column NEXT to the column "One" and I will call it "One_new":

When filling this column with values I will follow the following rule:

If the value in column "One" is less than 1 (index[1]) and greater than -1(-index[1]) then 0.

If the value in column "One" is greater than 1 (index[1]) and less than 2*(index[1]) then 1.

If the value in column "One" is greater than 2*(index[1]) it is set to 2.

If the value in column "One" is less than -1*(index[1]) and greater than -2*(index[1]) it is given the value -1.

If the value in column "One" is less than -2*(index[1]) it is given the value -2.

I’m gonna go through that rule for all the columns. What changes is the reference value that for the second column sera index[2], for the third index[3],...,up to the column 10 index[10]

I need those created columns to be next to the columns. That is, the One_new column should be next to the One column, the Two_new column next to the Two column and so on.

I can do that with the dplyr package?

Some help?

1 answer

4


I’d do it this way, using purrr and dplyr.

res <- map2_dfc(df, index, function(x, index) {
  case_when(
    x < -2*index ~ -2,
    x < -1*index ~ -1,
    x <  1*index  ~  0,
    x <  2*index  ~  1,
    TRUE         ~  2
    )
}) %>%
  set_names(paste0(names(.), "_new")) %>%
  bind_cols(df)

The function map2 of purrr is used to apply the function to each column of the data.frame and index.

Note that the final result does not put the columns side by side. This could be done using the function later select.

To select in the order you want, it is possible to do so:

res %>%
  select(flatten_chr(map(colnames(df), ~c(.x , paste0(.x , "_new")))))
  • Good Daniel worked perfectly. To use the select command I must make the "match" of the column names right? Each "match" I put the two columns together and by ne goes?

  • 1

    I made an example of how it can be done. I don’t know if it would be the best way..

  • 1

    I always ask. Thank you again.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.