我是R的新手,请原谅我的无知。
我有一个由两个变量组成的数据框:位置和响应。我有另一个数据框,包括每个位置的采样工作量。我需要使用位置作为标识符,通过采样工作来划分响应。我知道可能有一个简单的解决方案,但我很惊讶地发现它。我将不胜感激任何帮助。
Example:
Dataframe 1
Location Response
Loc1 25
Loc2 63
Loc3 5.63
Dataframe2
Location Sampling effort
Loc1 2
Loc2 6.5
Loc3 3
答案 0 :(得分:4)
您可以使用merge()
合并它们,然后只划分两列:
df3 <- merge(df1, df2)
df3$solution <- df3$Response / df3$Sampling_effort
df3
# Location Response Sampling_effort solution
# 1 Loc1 25.00 2.0 12.500000
# 2 Loc2 63.00 6.5 9.692308
# 3 Loc3 5.63 3.0 1.876667
我使用了数据:
df1 <- structure(list(Location = structure(1:3, .Label = c("Loc1", "Loc2",
"Loc3"), class = "factor"), Response = c(25, 63, 5.63)), .Names = c("Location",
"Response"), class = "data.frame", row.names = c(NA, -3L))
df2 <- structure(list(Location = structure(1:3, .Label = c("Loc1", "Loc2",
"Loc3"), class = "factor"), Sampling_effort = c(2, 6.5, 3)), .Names = c("Location",
"Sampling_effort"), class = "data.frame", row.names = c(NA, -3L))
答案 1 :(得分:1)
df1$Response/df2$Sampling_effort[match(df1$Location, df2$Location)]
#[1] 12.500000 9.692308 1.876667
答案 2 :(得分:1)
dplyr
/ tidyverse
方法:
df1 <-
read.table(text = "Location Response
Loc1 25
Loc2 63
Loc3 5.63
", header = TRUE, stringsAsFactors = FALSE)
df2 <-
read.table(text = "Location Sampling_effort
Loc1 2
Loc2 6.5
Loc3 3
", header = TRUE, stringsAsFactors = FALSE)
library(dplyr)
df_joined <-
df1 %>%
left_join(df2) %>%
mutate(Effect_size = Response / Sampling_effort)
导致:
> df_joined Location Response Sampling_effort Effect_size 1 Loc1 25.00 2.0 12.500000 2 Loc2 63.00 6.5 9.692308 3 Loc3 5.63 3.0 1.876667
在R中操作数据有很多很好的介绍,但我们确实发现数据广告是有用的 - 虽然它不再是免费的。
答案 3 :(得分:0)
由于您的数据框遵循相同的顺序,因此
就足够了df1[,2]/df2[,2]