Including columns in a dataframe in R using a rule

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 index 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 in the values -2, -1, 0, 1 or 2 in these columns created according to a rule.

It would look like this: I will create a column ON THE SIDE of the column "One" and I will call it "One_new":

At the time of populating this column with values I will follow the following rule:

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

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

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

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

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

I'll go through this rule for all columns. What changes is the reference value that for the second column will be index [2], for the third index [3], ..., up to the one for column 10 index [10]

I need these 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.

Can I do this with the dplyr package?

Any help?

    
asked by anonymous 20.09.2018 / 00:00

1 answer

4

I would 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 map2 function of purrr is used to apply the function for each column of data.frame and index.

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

To select in the order you want, you can do this:

res %>%
  select(flatten_chr(map(colnames(df), ~c(.x , paste0(.x , "_new")))))
    
20.09.2018 / 01:51