我有一个小数据框,如下所示.

sad <- structure(list(a = c(1, 2), b = c(3, 4)), class = "data.frame", row.names = c(NA, -2L), class = c("tbl_df", "tbl", 
           "data.frame"))

有人能帮我了解一下下面的操作吗?

 sad[, a := sad[, "Ma"] == "Y"]
# A tibble: 2 x 2
      a     b
  <dbl> <dbl>
1     1     3
2     2     4

当我执行上述操作时,我得到了相同的输出,但不确定这里的目的是什么.有人能帮我吗?

推荐答案

Update:经过研究,我发现:What are the differences between "=" and "<-" assignment operators in R?

@Konrad Rudolf的答案讨论了=<-之间的区别,有趣的是,用<-代替=会抛出一个错误:

# in contrast to sad[, a = anything_here]

sad[, a <- anything_here]

error: Error in `[.tbl_df`(sad, , a <- anything) : object 'anything' not found`

如果你用<-,也可以用your example

sad[, a <- sad[, "Ma"] == "Y"]

从@Nosredna所提到的网站回答中得出结论:

"谷歌的R风格指南通过禁止在作业(job)中使用"="来简化问题.这是一个不错的 Select ."

So all in all maybe it is an assignement issue.

First answer:

让我们考虑一下:把右边的逗号分解成columns.另一方面,逗号的左侧将对行进行操作:

还可以考虑@onyanbu在 comments 中指出的:

# will not work no column a (a is a object)

sad[, a]

# All rows and the column named "a" -> this will work
sad[, 'a']

# will not work because you want to get all rows and column "Ma" -> there is no colum Ma in sad
sad[, "Ma"]

# here you assign nothing to object a
a = sad[, "Ma"]

# consecutevily you compare a = sad[, "Ma"] (e.g. nothing) to string 'Y'
# will not work because 'Ma' column don't exist.
sad[, "Ma"] == "Y"

R相关问答推荐

如何使用R中的dhrr函数将李克特量表的因子列从长转换为宽?

查找图下的面积

更改默认系列1以更改名称

使用tidy—select创建一个新的带有mutate的摘要变量

用值序列对行进行子集化,并标识序列开始的列

如何在观测缺失的地方添加零

找出二叉树中每个 node 在R中的深度?

根据另一列中的值和条件查找新列的值

将全局环境变量的名称分配给列表中的所有元素

如何平滑或忽略R中变量的微小变化?

扩展R中包含列表的数据框

删除数据帧中特定行号之间的每第三行和第四行

计算使一组输入值最小化的a、b和c的值

如何使用ggplot2根据绘图中生成的斜率对小平面进行排序?

R-如何在ggplot2中显示具有不同x轴值(日期)的多行?

如何修改GT表中组名行的 colored颜色 ?

将仪表板中的值框大小更改为Quarto

在R中,如果一个值在同一数据帧中的任何特定列中,如何计算?

根据小时-分钟列创建年-月-日序列

仅在Quarto中运行块的一部分