Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 我如何用一些指示符制作一个列?_R_Dataframe - Fatal编程技术网

R 我如何用一些指示符制作一个列?

R 我如何用一些指示符制作一个列?,r,dataframe,R,Dataframe,我有4个指示器和一个id行。我如何就这个指标创建一个列,如下所示: ID. col1. col2. col3. col4. 1 1 0 0 0 2 0 0 0 1 3 0 0 1 0 在每行中,只有一列为1,其他列为0。如果col1为1,则新列为1;如果col2为1,则新列为2;如果col3为1,则新列为3;如果col

我有4个指示器和一个id行。我如何就这个指标创建一个列,如下所示:

  ID.   col1.   col2.   col3.   col4. 
   1      1       0       0       0
   2      0       0       0       1
   3      0       0       1       0
在每行中,只有一列为1,其他列为0。如果col1为1,则新列为1;如果col2为1,则新列为2;如果col3为1,则新列为3;如果col4为1,则新列为4

所以输出是

  ID.   col.    
   1      1      
   2      4      
   3      3     

一个选项是
max.col

cbind(df1[1], `col.` = max.col(df1[-1], "first"))
#    ID. col.
#1   1    1
#2   2    4
#3   3    3

如果行中没有1,则创建一个逻辑条件,将该行返回为
NA

df1[2, 5] <- 0
cbind(df1[1], `col.` =  max.col(df1[-1], "first") * NA^ !rowSums(df1[-1] == 1))
df1[2,5]
df1 <- structure(list(ID. = 1:3, col1. = c(1L, 0L, 0L), col2. = c(0L, 
0L, 0L), col3. = c(0L, 0L, 1L), col4. = c(0L, 1L, 0L)), 
class = "data.frame", row.names = c(NA, 
-3L))