根据条件更改特定列中的值,而不更改其他值。在 R

问题描述 投票:0回答:1

我有一个包含值 1-6 的列的数据框,我想将其更改为 1-3 我想要的是:1=1,2=1, 3=2, 4=2, 5=3, 6=3。 我想在我的专栏中更改此名称:

sub1.4
sub2.4
sub3.4
sub4.4
sub5.4
sub6.4
sub7.4
sub8.4
sub9.3
sub10.4
sub 11.4
,
sub 12.4
,
sub13.4
,
sub14.4
,
sub15.4
,
sub16.4
,
sub17.3
,
sub18.4
,
sub20.4
.

但是,当我更改一个值时,它会在调整以下值时更改该值。例如:我把 5 变成 3,当我把 3 变成 2 时,它也会将“新”3 变成 2。

我想将数据框的当前状态更改为上述状态。

我试过:

     B_data1[B_data1 == 5] <- 3                    #turn all value 5 into 3 in B_data
        B_data1[B_data1 == 6] <- 3                 #turn all value 6 into 3 in B_data
        B_data1$sub1.4[B_data1$sub1.4<2] <- 1      #turn all value 2 into 1 in B_data$.. 'specifc column'
        B_data1$sub1.4[B_data1$sub1.4<3] <- 2      #turn all value 3 into 2 in B_data$.. 'specifc column'
        B_data1$sub1.4[B_data1$sub1.4<4] <- 2      #turn all value 4 into 2 in B_data$.. 'specifc column'
        ... 
#NOTE: value 5 and 6 are only present in the above (first alinea) stated columns, values 1-4 are also present in different columns of which I don't want to change the value of

这将导致“循环问题”,新值也会发生变化。 如何将特定列的值更改为不同的值,而不是在更改不同的值时更改它?

示例数据集(这个数据集在所有列中都有 1-6,但是如上所述,我的数据集仅在特定列中有 1-6):

B_data1 <- data.frame(matrix(0, nrow = 51, ncol = 41))
# Set the column names for the first column and items columns
colnames(B_data1) <- c("ID", paste(rep(paste0("sub", 1:20), each = 2), c("_1", "_2"), sep = ""))
# Fill the ID column with values 1 to 51
B_data1$ID <- 1:51
# Fill the item columns with random 0's and 1's
set.seed(123) # Set seed for reproducibility
B_data1[, 2:41] <- matrix(sample(c(1:6), size = 20 * 2 * 51, replace = TRUE), ncol = 40)
# Show the resulting data frame
B_data1

编辑:

我通过以下代码解决了这个问题:

B_data1[,c("sub1.4","sub2.4", "sub3.4", "sub4.4", "sub5.4", "sub6.4", "sub7.4", "sub8.4", "sub9.3", "sub10.4", "sub11.4", "sub12.4", "sub13.4", "sub14.4",
           "sub15.4", "sub16.4", "sub17.3", "sub18.4", "sub20.4")]<- ifelse(is.na(B_data1$sub1.4), NA, 
                                                                            ifelse(B_data1$sub1.4 %in% c(1,2), 1, 
                                                                                   ifelse(B_data1$sub1.4 %in% c(3,4), 2, 3)))
r dataframe sorting rscript
1个回答
0
投票

虽然 R 通常提供许多不同的方法来重命名变量值(您可以阅读here关于数据类型“factor”),但在您的情况下,最简单的解决方案可能是将整数除以 2 并应用

ceiling()
函数:

recode <- function(column) {
  ceiling(column/2)
  }

table(items$item1_1, recode(items$item1_1))
#      1  2  3
#   1  9  0  0
#   2  8  0  0
#   3  0 11  0
#   4  0  6  0
#   5  0  0 10
#   6  0  0  7
© www.soinside.com 2019 - 2024. All rights reserved.