我看过R create a vector from conditional operation on matrix,使用类似的解决方案并不能得到我想要的结果(我不知道为什么)。
我的目标是用以下条件评估df:if df > 2, df -2, else 0
以df:
a <- seq(1,5)
b <- seq(0,4)
df <- cbind(a,b) %>% as.data.frame()df只是:
a b
1 0
2 1
3 2
4 3
5 4在一个适当的函数之后,df_final应该是这样的:
a b
0 0
0 0
1 0
2 1
3 2我应用了下面的函数并给出了结果,我不知道为什么它不能工作(如果能对解决方案作进一步的解释,我将不胜感激)
apply(df,2,function(df){
ifelse(any(df>2),df-2,0)
})产生以下结果:
a b
-1 -2谢谢大家!
发布于 2018-11-08 21:36:53
让我们修复您的函数,并理解它为什么不起作用:
apply(df, # apply to df
2, # to each *column* of df
function(df){ # this function. Call the function argument (each column) df
# (confusing because this is the same name as the data frame...)
ifelse( # Looking at each column...
any(df > 2), # if there are any values > 2
df - 2, # then df - 2
0 # otherwise 0
)
})any()返回一个值。ifelse()返回与测试相同的形状,因此通过使测试any(df > 2) (单个值),ifelse()也将返回单个值。
让我们通过以下方法来解决这个问题:(a)将函数更改为与输入(可读性)不同的名称;(b)去掉any
apply(df, # apply to df
2, # to each *column* of df
function(x){ # this function. Call the function argument (each column) x
ifelse( # Looking at each column...
x > 2, # when x is > 2
df - 2, # make it x - 2
0 # otherwise 0
)
})apply是用来处理矩阵的。当你给它一个数据框架时,它做的第一件事就是把它转换成一个矩阵。如果希望结果是数据框架,则需要将其转换回数据框架。
或者我们可以用lapply代替。lapply返回一个list,通过将它分配给带有df[] <- lapply()的df列,我们不需要进行转换。(而且由于lapply不执行矩阵转换,因此默认情况下它知道将函数应用于每一列。)
df[] <- lapply(df, function(x) ifelse(x > 2, x - 2, 0))顺便提一句,df <- cbind(a,b) %>% as.data.frame()是一种更复杂的编写df <- data.frame(a, b)的方法。
发布于 2018-11-08 21:20:52
通过减去2创建“out”数据集,然后将基于逻辑条件的值替换为0
out <- df - 2
out[out < 0] <- 0或者一步一步
(df-2) * ((df - 2) > 0)发布于 2018-11-08 21:20:37
使用应用
a <- seq(1,5)
b <- seq(0,4)
df <- cbind(a,b) %>% as.data.frame()
new_matrix <- apply(df, MARGIN=2,function(i)ifelse(i >2, i-2,0))
new_matrix
###if you want it to return a tibble/df
new_tibble <- apply(df, MARGIN=2,function(i)ifelse(i >2, i-2,0)) %>% as_tibble()https://stackoverflow.com/questions/53216242
复制相似问题