如何在 R 資料框中找到每列值的平方根,其中某些列是分類的?


要在 R 資料框中找到每列值的平方根,其中某些列是分類的,我們可以按照以下步驟操作:

  • 首先,建立一個數據框。

  • 然後,使用 plyr 包中的 numcolwise 函式來找到每列值的平方根,其中某些列是分類的。

示例

建立資料框

讓我們建立一個如下所示的資料框:

Level<-sample(c("low","medium","high"),25,replace=TRUE)
Group<-sample(c("first","second"),25,replace=TRUE)
DV1<-sample(c(1,4,9,16,25,36,49,64,81,100),25,replace=TRUE)
DV2<-sample(c(1,4,9,16,25,36,49,64,81,100),25,replace=TRUE)
df<-data.frame(Level,Group,DV1,DV2)
df

輸出

執行上述指令碼後,將生成以下輸出(由於隨機化,此輸出在您的系統上可能會有所不同):

   Level  Group  DV1 DV2
1  high   second  49  64
2  medium second  64  64
3  high   second  64   4
4  medium second  81  49
5  medium second   9  64
6  low    second  64   4
7  low    second  49  64
8  high   first  100  81
9  high   second  49   9
10 high   second  81   1
11 medium second  64  64
12 low    second  64   4
13 high   first    4  81
14 medium second 100   1
15 low    first   16  16
16 high   second  64  36
17 high   first   81  16
18 high   first   16   9
19 high   first   81   1
20 high   second 100  16
21 low    second  25   9
22 medium first   36  16
23 high   first  100  64
24 high   first   25  36
25 high   second   1  49

在某些列為分類的情況下,查詢每列值的平方根

使用 plyr 包中的 numcolwise 函式在資料框 df 中查詢每列值的平方根,其中某些列是分類的:

Level<-sample(c("low","medium","high"),25,replace=TRUE)
Group<-sample(c("first","second"),25,replace=TRUE)
DV1<-sample(c(1,4,9,16,25,36,49,64,81,100),25,replace=TRUE)
DV2<-sample(c(1,4,9,16,25,36,49,64,81,100),25,replace=TRUE)
df<-data.frame(Level,Group,DV1,DV2)
library(plyr)
numcolwise(sqrt)(df)

輸出

   DV1 DV2
1   7  8
2   8  8
3   8  2
4   9  7
5   3  8
6   8  2
7   7  8
8  10  9
9   7  3
10  9  1
11  8  8
12  8  2
13  2  9
14 10  1
15  4  4
16  8  6
17  9  4
18  4  3
19  9  1
20 10  4
21  5  3
22  6  4
23 10  8
24  5  6
25  1  7

更新於:2021年11月9日

176 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.