我正在R。
我有两个tibbles
/ data.frames
值,均由一列year
索引。
第一个小标题df
-包含n years
的值(不一定唯一,但可以是唯一的),第二个小标题-df1
-包含每个year
的第一个的乘法值(在这种情况下,仅unique(year)
个值)。
我要做的是将第一矩阵的每个元素乘以第二矩阵的正确引用。
Year <- c("2010", "2010", "2011", "2011")
value <- c(1, 2, 3, 4)
df <- as_tibble(value) %>% add_column(Year= Year)
Year1<- c("2010", "2011")
value1 <- c(100, 200)
df1 <- as_tibble(value1) %>% add_column(Year1= Year1)
此示例的结果应为以下内容(但可扩展为动态dim(df)
/ dim(df1)
:
result <- c(100, 200, 600, 800)
res <- as_tibble(result) %>% add_column(Year = Year)
任何想法我该如何实现?非常感谢。
答案 0 :(得分:2)
我们可以在“年份”列中加入processData
,然后将“值”列相乘
function processData(data, json) {
const combinators = ["OR", "AND"]
function leafValue(item) {
switch (item.operator) {
case '=':
return data[item.value] === item.expression
}
throw new Error(`unknown comparison operator ${item.operator}`)
}
function evaluate(json) {
const evaluated = json.map(item => Array.isArray(item) ? evaluate(item) : item)
while (evaluated.length >= 3) {
const chunk = [evaluated[0], evaluated[1], evaluated[2]]
const combinator = chunk.find(item => combinators.includes(item))
const [A, B] = chunk.filter(item => !combinators.includes(item))
const valueA = typeof A === 'boolean' ? A : leafValue(A)
const valueB = typeof B === 'boolean' ? B : leafValue(B)
const result = combinator === 'OR' ?
(valueA || valueB) :
(valueA && valueB)
evaluated.splice(0, 3, result)
}
return evaluated[0]
}
return evaluate(json)
}
const json = {
"truthy": [
[
"AND",
{
"operator": "=",
"compareType": "text",
"value": "fname",
"expression": "John"
},
{
"operator": "=",
"compareType": "text",
"value": "lname",
"expression": "Doe"
}
],
"OR",
{
"operator": "=",
"compareType": "boolean",
"value": "Agree",
"expression": true
},
"OR", [
"AND",
{
"operator": "=",
"compareType": "text",
"value": "fname",
"expression": "Jane"
},
{
"operator": "=",
"compareType": "text",
"value": "lname",
"expression": "Doe"
}
]
]
}
const data = {
fname: 'John',
lname: 'Doe',
}
const result = processData(data, json.truthy)
console.log(result)
或者使用by
连接并通过将“值”乘以第二个数据集(library(dplyr)
df %>%
left_join(df1, by = c('Year' = 'Year1')) %>%
transmute(value = value.x * value.y, Year)
)的“值”列来分配(data.table
)“值”
:=
答案 1 :(得分:2)
这是使用merge
transform(
merge(df, df1, by.x = "Year", by.y = "Year1"),
value = value.x * value.y
)[names(df)]
给出
value Year
1 100 2010
2 200 2010
3 600 2011
4 800 2011