如何在 R 中新增變數描述?
要在 R 中新增變數描述,我們可以使用評論函式,如果我們想檢視描述,則將使用資料框的結構呼叫。例如,如果我們有一個數據框,比如 df,其中包含一個列 x,那麼我們可以使用命令 comment(df$x)<-c("此變數的名稱為 x") 來描述 x。現在,要檢視它,我們可以使用 str(df)。
示例 1
考慮以下資料框 −
x1<-rnorm(20,21,3.24) x2<-rnorm(20,5,2.1) df1<-data.frame(x1,x2) df1
輸出
x1 x2 1 23.12252 5.085650 2 19.81415 5.180194 3 14.41423 2.756885 4 21.34914 5.714200 5 18.34662 3.814034 6 21.37762 9.538720 7 21.48240 4.838389 8 22.58701 2.185943 9 15.68257 5.084348 10 20.86272 5.732107 11 19.84529 3.430304 12 26.23832 3.684373 13 25.35179 5.001748 14 19.83831 3.393473 15 23.57819 5.057545 16 15.69374 7.442210 17 15.69028 6.722865 18 18.94718 8.046787 19 25.26722 2.776823 20 23.32905 3.561213
str(df1)
'data.frame': 20 obs. of 2 variables: $ x1: num 23.1 19.8 14.4 21.3 18.3 ... $ x2: num 5.09 5.18 2.76 5.71 3.81 ...
在 df1 中新增變數描述 −
comment(df1$x1)<-c("This variable follows normal distribution")
comment(df1$x2)<-c("This variable follows normal distribution")
str(df1)'data.frame':20 個包含 2 個變數的 obs −
$ x1: num 23.1 19.8 14.4 21.3 18.3 ... ..- attr(*, "comment")= chr "This variable follows normal distribution" $ x2: num 5.09 5.18 2.76 5.71 3.81 ... ..- attr(*, "comment")= chr "This variable follows normal distribution"
示例 2
y1<-sample(0:1,20,replace=TRUE) y2<-sample(LETTERS[1:5],20,replace=TRUE) df2<-data.frame(y1,y2) df2
輸出
y1 y2 1 0 B 2 1 E 3 0 B 4 1 A 5 1 D 6 0 A 7 0 E 8 1 D 9 0 D 10 0 D 11 0 E 12 0 C 13 1 A 14 1 D 15 0 B 16 0 E 17 1 C 18 0 C 19 1 D 20 1 C
str(df2)
'data.frame': 20 obs. of 2 variables: $ y1: int 0 1 0 1 1 0 0 1 0 0 ... $ y2: chr "B" "E" "B" "A" ...
在 df2 中新增變數描述 −
comment(df2$y1)<-c("This is a binary variable")
comment(df2$y2)<-c("This is a categorical variable")
str(df2)'data.frame':20 個包含 2 個變數的 obs −
$ y1: int 0 1 0 1 1 0 0 1 0 0 ... ..- attr(*, "comment")= chr "This is a binary variable" $ y2: chr "B" "E" "B" "A" ... ..- attr(*, "comment")= chr "This is a categorical variable"
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP