gpt4 book ai didi

rowMeans 如果列名是数字

转载 作者:行者123 更新时间:2023-12-01 11:29:26 25 4
gpt4 key购买 nike

我的数据框看起来像:

我的数据看起来像..

 Tester Type    Subject Type    Time        1     2     3
TType1 SType1 Day 1 11 2 1
TType1 SType2 Day 1 3 2 13
TType1 SType1 Day 2 2 3 15
TType2 SType3 Day 2 1 4 3
TType3 SType3 Day 2 2 3 4
TType1 SType1 Day 1 7 2 2
TType2 SType1 Day 2 2 6 7

所以我的列名是 c(Tester.Type, Subject.Type, Time, 1, 2, 3)

我想创建一个计算行均值的列,但前提是列名是数字。

我知道如何直接去做:

avgdata <- rowMeans(data[,c(4:6)],na.rm=TRUE)

但是有没有一种编码方式可以在列名是数字 (is.numeric) 时自动获取?

这样一来,如果我有更多带有数字列名的列,我就不必更改列范围了吗?

谢谢。

最佳答案

当您读入数据时。请记住使用参数 check.names=F

df1 <- read.table(text="
TesterType SubjectType Time 1 2 3
TType1 SType1 Day1 11 2 1
TType1 SType2 Day1 3 2 13
TType1 SType1 Day2 2 3 15
TType2 SType3 Day2 1 4 3
TType3 SType3 Day2 2 3 4
TType1 SType1 Day1 7 2 2
TType2 SType1 Day2 2 6 7",
head=T, as.is=T, check.names = F)

df1
rowMeans(df1[colnames(df1)[!is.na(as.numeric(colnames(df1)))]])
# [1] 4.666667 6.000000 6.666667 2.666667 3.000000 3.666667 5.000000

or using regular expression.

rowMeans(df1[colnames(df1)[grepl("^\\d+$", colnames(df1))]])
# [1] 4.666667 6.000000 6.666667 2.666667 3.000000 3.666667 5.000000

关于rowMeans 如果列名是数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34146769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com