[英]R list/table manipulation replacing “for” loop with sapply?
我試圖在R只是用一個簡單的常量添加到表的列,例如
dim(exampletable)
[1] 3900 2
在第二列上添加值,我的工作是:
newtable <- exampletable
for (i in 1:nrow(newtable)){newtable[i,2] <- exampletable[i,2] + constant}
但這似乎有點矯kill過正。 sapply說,還有更優雅的方法嗎?
謝謝,約翰尼斯
R是向量化的,並且對於其他語言中往往更冗長的操作具有非常方便的語法。 您所描述的可能是您想要做的最糟糕的實現,並且幾乎與R的含義相反。 取而代之的是,使用R的內置矢量化技術,過上幸福的長壽!
有很多方法可以做到這一點,但是規范的方法(除了使用列索引整數而不是列名)是:
newtable[,2] <- newtable[,2] + constant
例如
df <- data.frame( x = 1:3 )
df$y <- df$x + 1
df
# x y
#1 1 2
#2 2 3
#3 3 4
我建議在R上的基礎知識閱讀起來有幾個很好的教程的信息頁面中的r
標記。
嘗試這個:
#Dummy data
exampletable <- data.frame(x=runif(3900), y=runif(3900))
#Define new constant
MyConstant <- 10
#Make newtable with MyConstant update
newtable <- exampletable
newtable$y <- newtable$y + MyConstant
這是R語言的基礎,請閱讀一些手冊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.