从cor.test结果创建数据帧时转换变量类型

时间:2011-12-28 10:06:58

标签: r dataframe

以下数据集和代码创建一个新数据集,其中cor.test的结果是从我原始数据集对每个个体('Individual_ID')执行的。如何将每个变量从cor.test结果转换为数字数据类型,因为它被传递到新的数据帧?例如,'estimate','p.value'和'conf.int'应该是数字而不是字符。其次,我希望变量'conf.int'是两个变量,'lowlim'和'uplim'。

## Create sample dataset
WW_Wing_SI <-
structure(list(Individual_ID = c("WW_08A_02", "WW_08A_02", "WW_08A_02",
"WW_08A_02", "WW_08A_02", "WW_08A_02", "WW_08A_02", "WW_08A_02",
"WW_08A_02", "WW_08A_03", "WW_08A_03", "WW_08A_03", "WW_08A_03",
"WW_08A_03", "WW_08A_03", "WW_08A_03", "WW_08A_03", "WW_08A_03"
), FeatherPosition = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4,
5, 6, 7, 8, 9), Delta13C = c(-18.67, -19.16, -20.38, -20.96,
-21.61, -21.65, -21.31, -20.8, -21.28, -20.06, -20.3, -21.21,
-22.9, -22.87, -21.13, -20.68, -20.58, -20.69)), .Names = c("Individual_ID",
"FeatherPosition", "Delta13C"), row.names = c(NA, 18L), class = "data.frame")

# split data frame according the the individual IDs
individual.list <- split(WW_Wing_SI, WW_Wing_SI$Individual_ID)

# apply cor.test() with extract to each element of the list
test <- as.data.frame(t(sapply(individual.list, function(temp)
                        cor.test(temp$Delta13C, temp$FeatherPosition,
                        method="pearson")[c("estimate", "p.value", "conf.int")])))

1 个答案:

答案 0 :(得分:4)

我就是这样做的。如果你所做的一切都“正确”,那么输出已经是数字的,所以不需要强制(如果不是,你会使用as.numeric(object$variable))。当我创建inter变量时,我插入所需的组件,以便我可以构造较低/较高的CI变量。请注意,test现在是一个“正确的”data.frame,可以更容易使用(您可以轻松提取所需的任何项目)。

# split data frame according the the individual IDs
individual.list <- split(WW_Wing_SI, WW_Wing_SI$Individual_ID)

# apply cor.test() with extract to each element of the list
inter <- sapply(individual.list, function(temp) {
            a <- cor.test(temp$Delta13C, temp$FeatherPosition,
                    method="pearson")[c("estimate", "p.value", "conf.int")]
            out <- data.frame(cor = a$estimate, p.value = a$p.value, lowerCI = a$conf.int[1], upperCI = a$conf.int[2])
        }, simplify = FALSE)
test <- do.call("rbind", inter)
test

                  cor    p.value    lowerCI    upperCI
WW_08A_02 -0.76706752 0.01585509 -0.9481677 -0.2098478
WW_08A_03 -0.02320767 0.95274294 -0.6768966  0.6509469