我對 R 相當陌生,在 Youtube 上參加了 2 小時的免費課程后,我感覺好不了多少。我正在努力學習,所以我希望有人可以幫助我!我感覺接近答案,但我在這里:DI 有一個資料集,并且我通過將它們編輯為字串(字符)來修改這兩列。它們由人的名字(第一列)和姓氏(第二列)組成,因此我被命令洗掉標點符號,因此不得不將它們編輯為字串。現在我不確定如何將它們添加回資料框中。這就是我所在的地方。
# FILE: Vaccine_CSV
# INSTALL AND LOAD PACKAGES
library(datasets) # Load base packages manually
# Use pacman to load add-on packages as desired
pacman::p_load(pacman, rio)
# Importing CSV from desktop
Vaccine_CSV <- import("~/Desktop/Vaccine CSV.csv")
# Summary
summary(Vaccine_CSV)
# Transform lowercases in data into upper case
Vaccine_CSV = as.data.frame(sapply(Vaccine_CSV, toupper))
Vaccine_CSV$FirstName
Vaccine_CSV$LastName
# Trim the spaces between the names
trimws(Vaccine_CSV$FirstName)
trimws(Vaccine_CSV$LastName)
# First and last names combined
FirstNameFixed<- Vaccine_CSV [, c(3)]
LastNFixed<- Vaccine_CSV [, c(4)]
# Trimming inside the first name column
FirstNameFixed <- gsub("\\-", "", FirstNameFixed)
FirstNameFixed <- gsub("\\s", "", FirstNameFixed)
FirstNameFixed <- gsub("\\'", "", FirstNameFixed)
# Trimming inside last name column
LastNFixed<- gsub("\\-", "", LastNFixed)
LastNFixed <- gsub("\\s", "", LastNFixed)
LastNFixed<- gsub("\\'", "", LastNFixed)
uj5u.com熱心網友回復:
我想dplyr包在這里會是朋友。
應用 toupper 后,您的代碼可以撰寫如下:
library(dplyr)
Vaccine_CSV$FirstName <- trimws(.) %>% gsub("\\-", "",.) %>% gsub("\\s", "",.) %>% gsub("\\'", "",.)
和資料框列將被更改。
另一方面,如果你想使用串列或向量而不是資料框,一旦你FirstNameFixed完成LastNFixed了所有操作,你可以將它們組合起來:
new_df <- cbind(FirstNameFixed,LastNFixed)
如果您想將它們替換為資料框:
Vaccine_CSV$FirstName <- FirstNameFixed
Vaccine_CSV$LastName <- LastNFixed
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/484963.html
