我是 R 新手,正在尝试对以下数据集的第三维 (10x10) 进行二分:
http://www.stat.washington.edu/~hoff/courses/567/Data/monks
看起来我应该能够像这样对行和列运行两个循环,但不起作用:
for (k in 1:10)
{ replace(k,1, k>1=1) }
这是我尝试弄清楚R的第二天,除了一点STATA经验之外没有任何背景。如有任何建议,我们将不胜感激。
最佳答案
由于数据是一个数组,因此在使用函数之前我会将其强制转换为 data.frame
。我不确定这是否是您最终想要的输出格式。
# Coerce to a `data.frame`
df <- as.data.frame(my_data)
# Apply a function to the columns that makes the variables binary (meaning if they are positive, its a 1, else # a 0). This is what `ifesle` does. For more info read: ?ifelse
res = apply(df, 2, function(x) ifelse(x > 0, 1, 0))
ROMUL.like1 BONAVEN.like1 AMBROSE.like1 BERTH.like1 PETER.like1 LOUIS.like1 VICTOR.like1
ROMUL 0 0 1 0 1 0 0
BONAVEN 1 0 0 0 0 0 1
AMBROSE 1 1 0 0 0 0 0
BERTH 0 0 0 0 1 1 0
PETER 0 0 0 1 0 0 0
LOUIS 1 0 0 1 0 0 0
关于r - 如何在 R 中二分数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21368678/