简体   繁体   中英

Creating a new column based on another column in R

I have a data frame that has things like "nasal_coronal" and "coronal" and I want to get rid of "nasal_" and create a new column for things marked with "nasal"

I initially tried to use grep() like this: data.df$nasal <- grep("^nasal", data$type, value = TRUE) but R gives me the error that the replacement has less rows than the data set.

Here's code to create a mini dataset.

type <- c("nasal_coronal", "nasal_coronal", "coronal")
word <- c("something", "walk", "thing")

data.df <- data.frame(word, type) 

If we need to create a column that indicates the 'type' column had nasal_ , we can use grep ie

data.df$initType <- grepl("nasal_", data.df$type)

Then using sub , we remove the substring that matches characters until _ for the 'type' column

data.df$type <- sub('.*_', '', data.df$type)

Adding/deleting columns in a data frame as follows:

 df <- data.frame(1:5, 21:25, 31:35)
 colnames(df) <-c("A","B","C")

 df

 A  B  C
 1 1 21 31
 2 2 22 32
 3 3 23 33
 4 4 24 34
 5 5 25 35

 # delete column "B":
 df$B <-NULL

 df

 df
 A  C
 1 1 31
 2 2 32
 3 3 33
 4 4 34
 5 5 35

 # add new column "extra": 

 df$extra <-rnorm(1:5)

 A  C      extra
 1 1 31  0.6739996
 2 2 32  1.0011144
 3 3 33 -0.1595998
 4 4 34  0.5696583
 5 5 35 -0.4564025

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM