How to swap row values in the same column of a data frame?

╄→гoц情女王★ 提交于 2021-01-29 06:36:13

问题


I have a data frame that looks like the following:

ID   Loc
 1    N  
 2    A   
 3    N
 4    H
 5    H  

I would like to swap A and H in the column Loc while not touching rows that have values of N, such that I get:

ID   Loc
 1    N  
 2    H   
 3    N
 4    A
 5    A 

This dataframe is the result of a pipe so I'm looking to see if it's possible to append this operation to the pipe.


回答1:


We can try chaining together two calls to ifelse, for a base R option:

df <- data.frame(ID=c(1:5), Loc=c("N", "A", "N", "H", "H"), stringsAsFactors=FALSE)
df$Loc <- ifelse(df$Loc=="A", "H", ifelse(df$Loc=="H", "A", df$Loc))
df

  ID Loc
1  1   N
2  2   H
3  3   N
4  4   A
5  5   A



回答2:


You could try:

df$Loc <- chartr("AH", "HA", df$Loc)
df

  ID Loc
1  1   N
2  2   H
3  3   N
4  4   A
5  5   A



回答3:


If you have a factor, you could simply reverse those levels

l <- levels(df$Loc)
l[l %in% c("A", "N")] <- c("N", "A")

df
#   ID Loc
# 1  1   A
# 2  2   N
# 3  3   A
# 4  4   H
# 5  5   H

Data:

df <- structure(list(ID = 1:5, Loc = structure(c(3L, 1L, 3L, 2L, 2L
), .Label = c("A", "H", "N"), class = "factor")), .Names = c("ID", 
"Loc"), class = "data.frame", row.names = c(NA, -5L))


来源:https://stackoverflow.com/questions/54898289/how-to-swap-row-values-in-the-same-column-of-a-data-frame

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!