我有一个包含五个变量的数据集(ft.mutate.topics) (四个数字是ft_technical、ft_performative、ft_procedural和ft_moral)。第五个是"topic_lab“,我希望它使用与其他四个变量中值最高的变量相关的名称(作为字符)。
下面将生成一个类似于我的数据集。
set.seed(1)
Data <- data.frame(
X = sample(1:10),
Y = sample(1:10),
Z = sample(1:10))对于一个变量--V--对于每一个对应于这三个变量中哪个变量的" X“、"Y”、og "Z“,作为X的一个例子,这又是相似的:
if (Data$X > Data$Y & Data$X > Data$Z) Data$label <- "X"
Warning message:
In if (Data$X > Data$Y & Data$X > Data$Z) Data$label <- "X":
the condition has length > 1 and only the first element will be used 关于我最初的示例,我尝试了以下几种方法,结合使用if-命令:
if (ft.mutate.topics$ft_technical > ft.mutate.topics$ft_performative &
ft.mutate.topics$ft_technical > ft.mutate.topics$ft_procedural &
ft.mutate.topics$ft_technical > ft.mutate.topics$ft_moral)
ft.mutate.topics$topic_lab = "technical"
if (ft.mutate.topics$ft_performative > ft.mutate.topics$ft_technical &
ft.mutate.topics$ft_performative > ft.mutate.topics$ft_procedural &
ft.mutate.topics$ft_performative > ft.mutate.topics$ft_moral)
ft.mutate.topics$topic_lab = "performative"
if (ft.mutate.topics$ft_procedural > ft.mutate.topics$ft_performative &
ft.mutate.topics$ft_procedural > ft.mutate.topics$ft_technical &
ft.mutate.topics$ft_procedural > ft.mutate.topics$ft_moral)
ft.mutate.topics$topic_lab = "procedural"
if (ft.mutate.topics$ft_moral > ft.mutate.topics$ft_performative &
ft.mutate.topics$ft_moral > ft.mutate.topics$ft_procedural &
ft.mutate.topics$ft_moral > ft.mutate.topics$ft_technical)
ft.mutate.topics$topic_lab = "moral"它说:“条件的长度> 1,只有第一个元素将被使用”,并将整个变量替换为"performative“,因为它是第1行中值最高的。有人知道发生了什么吗?
谢谢!
发布于 2018-12-28 18:32:42
这看起来很简单。我将使用一个虚构的数据集,以适应你的应该很容易。
nms <- sub("^ft_", "", names(ft))
ft$topic.lab <- apply(ft, 1, function(x) nms[which.max(x)])数据.
这是一个模拟数据集。
set.seed(1234)
n <- 20
ft <- data.frame(ft_X = rnorm(n, 0, 2),
ft_Y = rnorm(n, 0, 3),
ft_Z = rnorm(n, 0, 4))发布于 2018-12-28 18:52:08
您可以使用max.col获取最大的列索引。然后,您将数据文件的names子集如下所示。
Data$V <- names(Data)[max.col(Data)]这默认为随意分割纽带。
发布于 2018-12-28 18:29:41
下面是一种使用apply和which.max的可能方法:
# create a fake input with random data
set.seed(123)
DF <- data.frame(ft_technical=sample(1:10,10),
ft_performative=sample(1:10,10),
ft_procedural=sample(1:10,10),
ft_moral=sample(1:10,10))
# add the columns using apply and which.max
mx <- DF[,c('ft_technical','ft_performative','ft_procedural','ft_moral')]
DF$topic_lab <- c('technical','performative','procedural','moral')[apply(mx,1,which.max)]产出:
> DF
ft_technical ft_performative ft_procedural ft_moral topic_lab
1 3 10 9 10 performative
2 8 5 7 9 moral
3 4 6 6 6 performative
4 7 9 10 8 procedural
5 6 1 4 1 technical
6 1 7 8 3 procedural
7 10 8 3 4 technical
8 9 4 2 7 technical
9 2 3 1 5 moral
10 5 2 5 2 technicalhttps://stackoverflow.com/questions/53962733
复制相似问题