วิธีแปลงหลายคอลัมน์เป็นปัจจัยโดยใช้ dplyr
คุณสามารถใช้วิธีการต่อไปนี้เพื่อแปลงหลายคอลัมน์เป็นปัจจัยโดยใช้ฟังก์ชันในแพ็คเกจ dplyr :
วิธีที่ 1: แปลงคอลัมน์ที่ระบุเป็นตัวประกอบ
library (dplyr) df %>% mutate_at(c(' col1 ', ' col2 '), as. factor )
วิธีที่ 2: แปลงคอลัมน์อักขระทั้งหมดเป็นปัจจัย
library (dplyr) df %>% mutate_if(is. character , as. factor )
ตัวอย่างต่อไปนี้แสดงวิธีการใช้แต่ละวิธีในทางปฏิบัติ
ตัวอย่างที่ 1: แปลงคอลัมน์ที่ระบุเป็นตัวประกอบ
สมมติว่าเรามี data frame ต่อไปนี้ใน R:
#create data frame
df <- data. frame (team=c('A', 'A', 'A', 'B', 'B', 'C', 'C', 'D'),
position=c('G', 'G', 'F', 'F', 'G', 'G', 'F', 'F'),
starter=c('Y', 'Y', 'Y', 'N', 'N', 'Y', 'N', 'N'),
points=c(12, 24, 25, 35, 30, 14, 19, 11))
#view structure of data frame
str(df)
'data.frame': 8 obs. of 4 variables:
$ team: chr "A" "A" "A" "B" ...
$position: chr "G" "G" "F" "F" ...
$ starter: chr "Y" "Y" "Y" "N" ...
$ points: num 12 24 25 35 30 14 19 11
เราจะเห็นว่าคอลัมน์ ทีม ตำแหน่ง และ ผู้เริ่มต้น เป็นอักขระ ในขณะที่คอลัมน์ คะแนน เป็นตัวเลข
ในการแปลงเฉพาะคอลัมน์ ทีม และ ตำแหน่ง เป็นปัจจัย เราสามารถใช้ไวยากรณ์ต่อไปนี้:
library (dplyr) #convert team and position columns to factor df <- df %>% mutate_at(c(' team ', ' position '), as. factor ) #view structure of updated data frame str(df) 'data.frame': 8 obs. of 4 variables: $ team: Factor w/ 4 levels "A","B","C","D": 1 1 1 2 2 3 3 4 $ position: Factor w/ 2 levels "F","G": 2 2 1 1 2 2 1 1 $ starter: chr "Y" "Y" "Y" "N" ... $ points: num 12 24 25 35 30 14 19 11
เราจะเห็นว่าคอลัมน์ ทีม และ ตำแหน่ง ตอนนี้เป็นทั้งสองปัจจัย
ตัวอย่างที่ 2: แปลงคอลัมน์อักขระทั้งหมดเป็นตัวประกอบ
สมมติว่าเรามี data frame ต่อไปนี้ใน R:
#create data frame
df <- data. frame (team=c('A', 'A', 'A', 'B', 'B', 'C', 'C', 'D'),
position=c('G', 'G', 'F', 'F', 'G', 'G', 'F', 'F'),
starter=c('Y', 'Y', 'Y', 'N', 'N', 'Y', 'N', 'N'),
points=c(12, 24, 25, 35, 30, 14, 19, 11))
#view structure of data frame
str(df)
'data.frame': 8 obs. of 4 variables:
$ team: chr "A" "A" "A" "B" ...
$position: chr "G" "G" "F" "F" ...
$ starter: chr "Y" "Y" "Y" "N" ...
$ points: num 12 24 25 35 30 14 19 11
เราจะเห็นว่าสามคอลัมน์ใน data frame เป็นคอลัมน์อักขระ
ในการแปลงคอลัมน์อักขระทั้งหมดเป็นปัจจัย เราสามารถใช้ไวยากรณ์ต่อไปนี้:
library (dplyr) #convert all character columns to factor df <- df %>% mutate_if(is. character , as. factor ) #view structure of updated data frame str(df) 'data.frame': 8 obs. of 4 variables: $ team: Factor w/ 4 levels "A","B","C","D": 1 1 1 2 2 3 3 4 $ position: Factor w/ 2 levels "F","G": 2 2 1 1 2 2 1 1 $ starter: Factor w/ 2 levels "N","Y": 2 2 2 1 1 2 1 1 $ points: num 12 24 25 35 30 14 19 11
เราจะเห็นว่าคอลัมน์อักขระทั้งหมดเป็นปัจจัยแล้ว
หมายเหตุ : โปรดดู หน้าเอกสารประกอบ dplyr สำหรับคำอธิบายแบบเต็มของฟังก์ชัน mutate_at และ mutate_if
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีดำเนินการทั่วไปอื่นๆ ใน R:
วิธีแปลงหลายคอลัมน์เป็นตัวเลขโดยใช้ dplyr
วิธีแปลงปัจจัยเป็นตัวเลขใน R
วิธีแปลงวันที่เป็นตัวเลขใน R