为什么基R`ifelse()`断断续续地将我的字符向量转换为矩阵? [英] Why does base R `ifelse()` turn my character vectors into matrices intermittently?

查看:70
本文介绍了为什么基R`ifelse()`断断续续地将我的字符向量转换为矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

library(tidyverse)
df <- tibble(col1 = c(5, 2), col2 = c(6, 4), col3 = c(9, 9))
# # A tibble: 2 x 3
#    col1  col2  col3
#   <dbl> <dbl> <dbl>
# 1     5     6     9
# 2     2     4     9


df.cha <- df %>% mutate(col4 = ifelse(apply(.[, 1:3], 1, sd) > 3,
                                      "True",
                                      "False"))
df.cha$col4
#[1] "False" "True" 

上面的代码可以正常工作.第4列是我希望的字符列.但是,我可以在ifelse语句中添加一个额外条件,即& .[, 3] > 0,突然之间R正在为第4列创建矩阵,而不是像我想要的那样将其保留为字符向量.见下文.

The code above works fine. Column 4 is a column of characters as I'd expect. However, I can add one extra condition to my ifelse statement, that being & .[, 3] > 0, and all of a sudden R is creating matrices for column 4 instead of leaving it as a character vector like I want. See below.

这是为什么?

df.mat <- df %>% mutate(col4 = ifelse(apply(.[, 1:3], 1, sd) > 3 & 
                                        .[, 3] > 0,  # I only added this
                                      "True",
                                      "False"))
df.mat$col4
#      col3   
# [1,] "False"
# [2,] "True" 

推荐答案

apply()首先将输入转换为矩阵,然后在该矩阵上运行sd()时,将得到一个简单的向量.

apply() converts your input to a matrix first, then when you run sd() across that matrix you get a simple vector.

但是当您对小标题进行.[,3]时,您会得到小标题.选择一列并不会像data.frames一样简化为向量.请注意,如果df是data.frame而不是tibble,则会得到不同的行为.

But when you do .[,3] with a tibble, you get a tibble back. Selecting one column does not simplify to a vector like it does with data.frames. Note that you would get different behavior if df were a data.frame rather than tibble.

所以ifelse()确实没有问题".事实是,您正在对小对象进行比较,以便保留形状而不是简化为矢量.碰巧的是,tibble +大于/小于-将按设计返回矩阵.

So the "problem" isn't with ifelse() really. It's the fact that you are doing comparisons on a tibble so the shape is preserved rather than simplified to a vector. And it just so happens that tibble + greater-than/less-than will return matrix by design.

这篇关于为什么基R`ifelse()`断断续续地将我的字符向量转换为矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆