本文介绍了有条件地将mutate_at应用于R中数据框中的特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R中有一个数据帧,如下所示:

I have a dataframe in R that looks like the following:

a  b  c  condition
1  4  2  acap
2  3  1  acap
2  4  3  acap
5  6  8  ncap
5  7  6  ncap
8  7  6  ncap

我试图重新记录条件ncap(以及此处未显示的其他两个条件)的a,b和c列中的值,同时保留这些值独自一人。

I am trying to recode the values in columns a, b, and c for condition ncap (and also 2 other conditions not pictured here) while leaving the values for acap alone.

以下代码适用于前3列。我试图弄清楚如何将其仅应用于按条件指定的行,同时将所有内容保留在同一数据框中。

The following code works when applied to the first 3 columns. I am trying to figure out how I can apply this only to rows that I specify by condition while keeping everything in the same dataframe.

df = df %>%
     mutate_at(vars(a:c), function(x) 
     case_when x == 5 ~ 1, x == 6 ~ 2, x == 7 ~ 3, x == 8 ~ 4)

这是预期的输出。

a  b  c  condition
1  4  2  acap
2  3  1  acap
2  4  3  acap
1  2  4  ncap
1  3  2  ncap
4  3  2  ncap

我一直在寻找这个问题的答案,但找不到。如果有人知道已经存在一个答案,我将不胜感激。

I've looked around for an answer to this question and am unable to find it. If someone knows of an answer that already exists, I would appreciate being directed to it.

推荐答案

我们可以使用 case_when 在使用 row_number 创建的条件下,即如果行号是4到6,则从该值中减去4,否则返回该值

We can use the case_when on a condition created with row_number i.e. if the row number is 4 to 6, subtract 4 from the value or else return the value

df %>% 
   mutate_at(vars(a:c), funs(case_when(row_number() %in% 4:6 ~ . - 4L, 
                                       TRUE ~ .)))
#  a b c condition
#1 1 4 2      acap
#2 2 3 1      acap
#3 2 4 3      acap
#4 1 2 4      ncap
#5 1 3 2      ncap
#6 4 3 2      ncap






如果这是基于值而不是行,请在值上创建条件


If this is based on the value instead of the rows, create the condition on the value

df %>% 
   mutate_at(vars(a:c), funs(case_when(. %in% 5:8 ~ . - 4L, 
                                       TRUE ~ .)))
#  a b c condition
#1 1 4 2      acap
#2 2 3 1      acap
#3 2 4 3      acap
#4 1 2 4      ncap
#5 1 3 2      ncap
#6 4 3 2      ncap






或者是否基于条件中的值


Or if it is based on the value in the 'condition'

df %>% 
   mutate_at(vars(a:c), funs(case_when(condition == 'ncap' ~ . - 4L, 
                                       TRUE ~ .)))






或者不使用任何 case_when

df %>% 
  mutate_at(vars(a:c), funs( . - c(0, 4)[(condition == 'ncap')+1]))
#  a b c condition
#1 1 4 2      acap
#2 2 3 1      acap
#3 2 4 3      acap
#4 1 2 4      ncap
#5 1 3 2      ncap
#6 4 3 2      ncap






base R ,我们可以通过创建索引来实现


In base R, we can do this by creating the index

i1 <- df$condition =='ncap'
df[i1, 1:3] <- df[i1, 1:3] - 4



数据



data

df <- structure(list(a = c(1L, 2L, 2L, 5L, 5L, 8L), b = c(4L, 3L, 4L, 
 6L, 7L, 7L), c = c(2L, 1L, 3L, 8L, 6L, 6L), condition = c("acap", 
 "acap", "acap", "ncap", "ncap", "ncap")), class = "data.frame", 
 row.names = c(NA, -6L))

这篇关于有条件地将mutate_at应用于R中数据框中的特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 16:25