![](/img/trans.png)
[英]Iterating through the rows a dataframe and changing the value of one column based on another
[英]Iterating through a vector and using that value as column of dataframe
我正在使用此for循環來標准化列中的數據。 這里m_sel_cols是帶有列名的向量。
for(i in m_sel_cols)
{
cal <- work_data1$i
cal <- ((cal-mean(cal))/sd(cal))
}
假設我的列名是“ A”,那么您可以這樣做:
...
cal <- work_data1$A
...
我的數據集中的列數非常大,我想將其轉換回數據幀,我知道可以使用cbind()
但是如何在for
循環中使用?
您可以使用sapply
在列中“循環”。
xy <- data.frame(a = 1:3, b = 4:6, c = 7:9)
sapply(xy, FUN = function(x) (x - mean(x))/sd(x))
a b c
[1,] -1 -1 -1
[2,] 0 0 0
[3,] 1 1 1
要么
> scale(xy)
a b c
[1,] -1 -1 -1
[2,] 0 0 0
[3,] 1 1 1
attr(,"scaled:center")
a b c
2 5 8
attr(,"scaled:scale")
a b c
1 1 1
我們可以用tidyverse
做到這tidyverse
library(tidyverse)
xy %>%
mutate_all(scale)
# a b c
#1 -1 -1 -1
#2 0 0 0
#3 1 1 1
xy <- data.frame(a = 1:3, b = 4:6, c = 7:9)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.