我非常努力地寻找答案,如果重复,我深表歉意。
我将制作一些虚拟数据来解释我的问题。
tibble(a=c(0.1, 0.2, 0.3), sample1 = c(0, 1, 1), sample2 = c(1, 1, 0))
# A tibble: 3 x 3
a sample1 sample2
<dbl> <dbl> <dbl>
1 0.1 0 1
2 0.2 1 1
3 0.3 1 0
如何有条件地更改 sample1 和 sample2 列中的值,以便如果它们等于 1,则它们采用 a 的值。
生成的小标题应该如下所示:
# A tibble: 3 x 3
a sample1 sample2
<dbl> <dbl> <dbl>
1 0.1 0 0.1
2 0.2 0.2 0.2
3 0.3 0.3 0
理想情况下,我不想对每个单独的示例列执行此操作(我有 >100 个示例列),因此循环列的方法会更好(尽管我知道循环是魔鬼)。
感谢您的帮助!
您可以将
mutate_at
与 ifelse
一起使用:
df %>% mutate_at(vars(starts_with('sample')), funs(ifelse(. == 1, a, .)))
# A tibble: 3 x 3
# a sample1 sample2
# <dbl> <dbl> <dbl>
#1 0.1 0.0 0.1
#2 0.2 0.2 0.2
#3 0.3 0.3 0.0
vars(starts_with('sample'))
匹配以 sample
开头的所有列,并且 mutate_at
将函数 funs(ifelse(. == 1, a, .))
应用于每一列; .
代表此处匹配的列。
如果您确定所有示例列仅包含
1
和 0
,则可以缩短为:
df %>% mutate_at(vars(starts_with('sample')), funs(. * a))
# A tibble: 3 x 3
# a sample1 sample2
# <dbl> <dbl> <dbl>
#1 0.1 0.0 0.1
#2 0.2 0.2 0.2
#3 0.3 0.3 0.0
使用
which()
的非 dplyr 解决方案:
> t=tibble(a=c(0.1, 0.2, 0.3), sample1 = c(0, 1, 1), sample2 = c(1, 1, 0))
> whichRows=which(t$sample1==t$sample2)
> t[whichRows,c('sample1','sample2')]<-t[whichRows,'a']
> t
# A tibble: 3 x 3
a sample1 sample2
<dbl> <dbl> <dbl>
1 0.1 0.0 1.0
2 0.2 0.2 0.2
3 0.3 1.0 0.0
一个
Base R
的方法:
数据
df <- data.frame(a=c(0.1, 0.2, 0.3), sample1 = c(0, 1, 1), sample2 = c(1, 1, 0))
程序
df[,2:ncol(df)] <- t(sapply(c(1:nrow(df)), function(x) ifelse(df[x,2:ncol(df)]==1, df[x,1],0)))
输出
df
a sample1 sample2
1 0.1 0.0 0.1
2 0.2 0.2 0.2
3 0.3 0.3 0.0