简体   繁体   中英

add a new column conditional on another character column in R

I have been trying to make a procedure in R. I want to ADD a new column base on several categories of another column. I put an example :

Column     New Column 
A              1
B              2
C              3
D              4
D              4
A              1

My question is how to add this new column with a particular value base on the values (in characters) of the first column.

It is really similar using the function of MUTATE and CASE_WHEN. The problem is that this function just takes into consideration numeric values and in this case I want take characters (categories) and base on this give a specific value to the new column.

Assuming you have a column of categories (not only letters), you can convert it to "ordered factors" to order the categories and then convert to integers.

x <- c("A", "B", "C", "D", "D", "A")
# make the dataframe 
v <- data.frame(x, as.integer(as.ordered(x)))
# 
colnames(v) <- c("Column", "New Column")
v
# output
> v
  Column New Column
1      A          1
2      B          2
3      C          3
4      D          4
5      D          4
6      A          1

If I understand you correctly you want to create a new column that has numbers corresponding to letters, with 1 corresponding to the first letter of the alphabet A, 2 corresponding to B, 3 to C, and so on. If that premise is correct, then this code will work for you:

ILLUSTRATIVE DATA

set.seed(12)
df <- data.frame(
  Column = sample(LETTERS[1:5],10, replace = T)
)
df
   Column
1       A
2       E
3       E
4       B
5       A
6       A
7       A
8       D
9       A
10      A

SOLUTION : Assign the indices of LETTERS , which is an ordered sequence of integers starting with 1, to the letters in df$COlumn where they match the letters in LETTERS :

df$Newcolumn <- seq(LETTERS)[match(df$Column, LETTERS)]

RESULt :

df
   Column Newcolumn
1       A         1
2       E         5
3       E         5
4       B         2
5       A         1
6       A         1
7       A         1
8       D         4
9       A         1
10      A         1

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