我正在尝试使用R中的tidyverse / dplyr包来处理数据,包括对在线API(来自Altmetric)的矢量化调用,以使用mutate添加行。
我可以创建的最小代码可以重现错误,如下所示。我收到错误“错误:不兼容的类型,期望一个数字向量”
library(tidyverse)
library(jsonlite)
fromJSON_wrapper <- function(x,y) {
fromJSON(x)[[c(y)]]
}
toy <- tibble(
doi = c("10.1002/anie.201500251", "10.1080/19443994.2015.1005695", "10.1007/s13721-015-0095-0"),
url = c("https://api.altmetric.com/v1/doi/10.1002/anie.201500251", "https://api.altmetric.com/v1/doi/10.1080/19443994.2015.1005695", "https://api.altmetric.com/v1/doi/10.1080/19443994.2015.1005695")
)
extracted <- toy %>% rowwise() %>% mutate(score = fromJSON_wrapper(url,"score"))
下面提取单个分数的代码可以使用,无论是使用包装还是单行搜索,我不知道为什么我的代码无效。
fromJSON_wrapper("https://api.altmetric.com/v1/doi/10.1007/s13721-015-0095-0")
extracted <- toy[1,] %>% rowwise() %>% mutate(score = fromJSON_wrapper(url, "score"))
任何建议都将不胜感激。
答案 0 :(得分:3)
只需迭代URL向量并提取所需内容就更简单了。 sapply
使这很简单,但library(tidyverse)
toy <- tibble(
doi = c("10.1002/anie.201500251", "10.1080/19443994.2015.1005695", "10.1007/s13721-015-0095-0"),
url = c("https://api.altmetric.com/v1/doi/10.1002/anie.201500251", "https://api.altmetric.com/v1/doi/10.1080/19443994.2015.1005695", "https://api.altmetric.com/v1/doi/10.1080/19443994.2015.1005695")
)
extracted <- toy %>% mutate(score = map_dbl(url, ~jsonlite::fromJSON(.x)$score))
extracted %>% select(doi, score)
#> # A tibble: 3 × 2
#> doi score
#> <chr> <dbl>
#> 1 10.1002/anie.201500251 0.25
#> 2 10.1080/19443994.2015.1005695 1.00
#> 3 10.1007/s13721-015-0095-0 1.00
也可以正常工作。
/* Write a program to compute and print the quartiles(quarter of the
* numbers with the largest values) of a set of integers
* The first quartile (Q1) is defined as the middle number between the smallest number and the median of the data set.
* The second quartile (Q2) is the median of the data.
* The third quartile (Q3) is the middle value between the median and the highest value of the data set.*/
#include <algorithm>
#include <iomanip>
#include <ios>
#include <iostream>
#include <string>
#include <vector>
using std::vector;
using std::endl;
using std::cout;
using std::cin;
int main() {
double x = 0;
double median, lowerQt, upperQt;
median = lowerQt = upperQt = 0;
vector<double> set;
typedef vector<double>::size_type vec_sz;
cout << "Enter integers followed by EOF: ";
while(cin >> x)
set.push_back(x);
vec_sz size = set.size();
if(size == 0) {
cout << "invalid" << endl;
return 1;
}
vec_sz mid = size / 2;
vec_sz lower = mid / 2;
vec_sz upper = size - mid;
sort(set.begin(), set.end());
median = size % 2 == 0 ? (set[mid] + set[mid - 1]) / 2 : set[mid];
lowerQt = mid % 2 == 0 ? (set[lower] + set[lower - 1]) / 2 : set[lower];
upperQt = mid % 2 == 0 ? (set[upper] + set[upper - 1]) / 2 : set[upper];
cout << lowerQt << endl << median << endl << upperQt;
}