我想將數據幀的備用列的值更改爲小於1的0。使用特定值提取數據幀中的列
abc 1 ghf 3
def 3 ftr 6
scf 0.2 ugh 1
小於1的第二列和第三列的所有值應該變爲零。
有沒有辦法在R?
我想將數據幀的備用列的值更改爲小於1的0。使用特定值提取數據幀中的列
abc 1 ghf 3
def 3 ftr 6
scf 0.2 ugh 1
小於1的第二列和第三列的所有值應該變爲零。
有沒有辦法在R?
這實際工作,並且可能難以以改善其簡單性:
df[ df<1 ] <- 0
替代的方法(但較不緊湊):當其用於與arr.ind=TRUE
返回行的兩列的矩陣和條件爲TRUE
的列。您可以使用[<-.data.frame
這一點,但它需要做的數字指標
idxs <- which(df <1, arr.ind=TRUE)
#Warning messages:
#1: In Ops.factor(left, right) : < not meaningful for factors
#2: In Ops.factor(left, right) : < not meaningful for factors
### Perfectly safe to ignore the warning
df[ idxs[,1], idxs[,2] ] <- 0
df
#------------------
V1 V2 V3 V4
1 abc 1 ghf 3
2 def 3 ftr 6
3 scf 0 ugh 1
,如果你給一個格式的數據,可以立即dput(myData)
使用,其輸出的可分配給一個變量,它會幫助:
> df <- structure(list(V1 = structure(1:3, .Label = c("abc", "def", "scf"
), class = "factor"), V2 = c(1, 3, 0.2), V3 = structure(c(2L, 1L,
3L), .Label = c("ftr", "ghf", "ugh"), class = "factor"), V4 = c(3L,
6L, 1L)), .Names = c("V1", "V2", "V3", "V4"), row.names = c(NA,
-3L), class = "data.frame")
> df
V1 V2 V3 V4
1 abc 1 ghf 3
2 def 3 ftr 6
3 scf 0.2 ugh 1
你說「的第二和第三的所有值專欄......「但你可能是指」第二和第四......「。這是我會做的:
> df$V2 <- ifelse(df$V2 < 1, 0, df$V2)
> df$V4 <- ifelse(df$V4 < 1, 0, df$V4)
> df
V1 V2 V3 V4
1 abc 1 ghf 3
2 def 3 ftr 6
3 scf 0 ugh 1
更多請參閱?ifelse
,但我認爲這應該有所幫助。
非常感謝。你的方式很容易做到。 – user1021713 2012-01-08 07:41:37