R 在不覆盖标题的情况下,向数据表中添加指定数量的空行
我试图创建一个带有标题行的大型空白data.table,以便在设置后在特定位置添加值。我已经能够复制第一行,然后清除或每一行,但我想做的是清除标题行之后的每一行。有些列是数字输入,有些是字符输入R 在不覆盖标题的情况下,向数据表中添加指定数量的空行,r,header,duplicates,data.table,row,R,Header,Duplicates,Data.table,Row,我试图创建一个带有标题行的大型空白data.table,以便在设置后在特定位置添加值。我已经能够复制第一行,然后清除或每一行,但我想做的是清除标题行之后的每一行。有些列是数字输入,有些是字符输入 [input3]: headers: header1 header2 header3..... header 60+ Values: NA NA NA ... NA 重复行: input3 <- input2[rep(1:nrow(input2), ea
[input3]:
headers: header1 header2 header3..... header 60+
Values: NA NA NA ... NA
重复行:
input3 <- input2[rep(1:nrow(input2), each = 2), ]
input3改用
input3[c(FALSE,2:nrow(input3) %% 1 == 0,] <- NA
这其中的“好处”是,,它(…)
返回一个整数的向量,因此它不需要与帧/表中的行数相同的长度
从?摘录(包括[
和朋友):
“循环利用”是长度1起作用的原因:它的逻辑值用于所有行。如果使用长度2,且行数为偶数(例如,mtcars[c(T,F),]
),则它将每隔一行给出一行。同样,如果假设循环利用,且没有偶数行(例如,mtcars[c(T,F,F),]
),那么你的假设就会变得不那么清晰
再加上data.table
的行为,它不会强制执行此操作。回收会给您带来麻烦,因此data.table
不鼓励这样做
library(data.table)
mt <- as.data.table(mtcars)
mt[c(T,F),] <- NA
# Error in `[.data.table`(x, i, which = TRUE) :
# i evaluates to a logical vector length 2 but there are 32 rows. Recycling of logical i is no longer allowed as it hides more bugs than is worth the rare convenience. Explicitly use rep(...,length=.N) if you really need to recycle.
mt[c(1,3),] <- NA
库(data.table)
mt使用input3[c(FALSE,2:nrow(input3)%%1==0),]我想我们缺少了一个括号k我用它来处理input3[c(FALSE,2:nrow(input3)%%1==0),]可能重复的警告:当我说“它必须是”时,我的意思是做其他的事情(依赖于回收)很容易出问题。最糟糕的情况是,当你想要的东西与它假设的不同时,它会默默地成功。
input3[c(FALSE,2:nrow(input3) %% 1 == 0,] <- NA
input3[which(2:nrow(input3) %% 1 == 0),] <- NA
For '['-indexing only: 'i', 'j', '...' can be logical
vectors, indicating elements/slices to select. Such vectors
are recycled if necessary to match the corresponding extent.
'i', 'j', '...' can also be negative integers, indicating
elements/slices to leave out of the selection.
library(data.table)
mt <- as.data.table(mtcars)
mt[c(T,F),] <- NA
# Error in `[.data.table`(x, i, which = TRUE) :
# i evaluates to a logical vector length 2 but there are 32 rows. Recycling of logical i is no longer allowed as it hides more bugs than is worth the rare convenience. Explicitly use rep(...,length=.N) if you really need to recycle.
mt[c(1,3),] <- NA