Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用magrittr有条件地替换值_R_Replace_Conditional_Magrittr - Fatal编程技术网

使用magrittr有条件地替换值

使用magrittr有条件地替换值,r,replace,conditional,magrittr,R,Replace,Conditional,Magrittr,假设我有一个数据帧,我想对其执行转换。 通常情况下,它看起来像: a <- data.frame(c(NA, 0,1), c(34,NA,0), c(3,9,NA) ) b <- c('key1', 'key2', 'key3') ####replace NA values with 0 a[is.na(a)] <- 0 ####replace 1 with 2 a[a==1] <- 2 ####sum rows a <- rowSums(a) ####bind b

假设我有一个数据帧,我想对其执行转换。 通常情况下,它看起来像:

a <- data.frame(c(NA, 0,1), c(34,NA,0), c(3,9,NA) )
b <- c('key1', 'key2', 'key3')
####replace NA values with 0
a[is.na(a)] <- 0
####replace 1 with 2
a[a==1] <- 2
####sum rows
a <- rowSums(a)
####bind b as key column for joining datasets in a later stage
c <- cbind(b, a)
给我:

[is.na(.)]中出错:“builtin”类型的对象不可子集
此外:警告消息:
In is.na(.):is.na()应用于“内置”类型的非-(列表或向量)


我们可以使用
dplyr

library(dplyr)
a %>%
    mutate_each(funs(replace(., is.na(.), 0))) %>% 
    mutate_each(funs(replace(., .==1, 2))) %>%
    rowSums(.) %>%
    data_frame(key = b, val = .)
#    key   val
#   <chr> <dbl>
#1  key1    37
#2  key2     9
#3  key3     2

我们可以使用
dplyr

library(dplyr)
a %>%
    mutate_each(funs(replace(., is.na(.), 0))) %>% 
    mutate_each(funs(replace(., .==1, 2))) %>%
    rowSums(.) %>%
    data_frame(key = b, val = .)
#    key   val
#   <chr> <dbl>
#1  key1    37
#2  key2     9
#3  key3     2
比@akrun建议的稍快一点(在键入方面,不确定在计算方面是否也快)的方法是使用-package中的
rec
函数:

库(sjmisc)
图书馆(dplyr)
a%
行和(%)%>%
数据帧(key=b,val=)
#一个tibble:3x2
#键值
#    
#1键1 37
#2键2 9
#3键3 2
使用-package中的
rec
函数比@akrun建议的方法稍快一点(在键入方面,不确定是否在计算方面也快):

库(sjmisc)
图书馆(dplyr)
a%
行和(%)%>%
数据帧(key=b,val=)
#一个tibble:3x2
#键值
#    
#1键1 37
#2键2 9
#3键3 2

谢谢,我更喜欢不使用其他软件包的方式。替换功能正是我想要的。谢谢,我更喜欢不使用其他软件包的方式。我一直在寻找替换函数。谢谢,当我有更大的替换列表时,我会记住此函数。谢谢,当我有更大的替换列表时,我会记住此函数。
 a %>% 
    is.na(.) %>%
    replace(a, ., 0) %>%
    replace(., .==1, 2) %>%
    rowSums() %>% 
    cbind(b, .)
library(sjmisc)
library(dplyr)

a <- data.frame(c(NA, 0,1), c(34,NA,0), c(3,9,NA) )
b <- c('key1', 'key2', 'key3')

a %>% 
  rec("NA=0;1=2;else=copy") %>% 
  rowSums(.) %>% 
  data_frame(key = b, val = .)

# A tibble: 3 x 2
#     key   val
#   <chr> <dbl>
# 1  key1    37
# 2  key2     9
# 3  key3     2