我在data.table
DataDia中有10列。
> head(DataDia[,c(7:16)])
Type soin 01 Type soin 02 Type soin 03 Type soin 04 Type soin 05 Type soin 06 Type soin 07 Type soin 08 Type soin 09 Type soin 10
1: crme de jour sérum démaquillant à rincer
2: masque démaquillant à rincer
3: crme de nuit sérum lotion
4: sérum lotion eau florale
5: crme de jour sérum démaquillant sans rinage
6: crme de nuit huile sérum
我只想将这些列的修改包含仅的常规函数应用于二进制值。如果列有空单元格,那么它将被0替换为else。 所以我写了这些代码:
DataDia[,DataDia[,c(5:10)]:=lapply(colnames(DataDia[,c(5:10)]), function(x) {if (DataDia[,x]==""){0} else {1}})]
但是我收到了这个错误:
[.data.table
中的错误(DataDia ,,:=
(DataDia [,c(7:16)], lapply(colnames(DataDia [,:LHS of:=必须是符号,或原子 矢量(列名或位置)。
请注意,我希望使用data.table
操作。但我不知道为什么这不起作用?
提前谢谢!
答案 0 :(得分:2)
首先,一个词汇点:你的细胞用""不是空单元格,但包含空字符串的单元格本身就是一个值。 "清空细胞"引用缺失值,在表格中显示为NA。
通常,在R中加载数据时(例如,通过na.strings =
函数中的read.table
参数),应该已经识别出缺失数据。如果你告诉我你是如何加载数据的,我可以帮助你解决这个问题。
至于你的代码,我会选择更简单的东西:
DataDia[,5:10] <- data.table(0+ !(DataDia[,5:10] == ""))
注意:此处使用0 +
部分为FALSE
获取0的数值,为TRUE
获取1的数值。感叹号用于测试写入条件的相反情况(当单元格为&#34;&#34;)时,我们希望它返回FALSE
或0。您需要data.table
函数,因为矩阵似乎不能正确强制data.table
。
以下是处理样本数据集的代码:
> DataDia
Produit1 Produit2 Produit3 Produit4
1: b c d
2: a b c
3: a c d
4: a b d
5: a c d
6: a b c d
7: b c d
8: a b c d
9: a b d
10: a b c d
> DataDia[,2:3] <- data.table(0+ !(DataDia[,2:3] == ""))
> DataDia
Produit1 Produit2 Produit3 Produit4
1: 1 1 d
2: a 1 1
3: a 0 1 d
4: a 1 0 d
5: a 0 1 d
6: a 1 1 d
7: 1 1 d
8: a 1 1 d
9: a 1 0 d
10: a 1 1 d