在进行数据分析时,有时需要将值重新编码为因子以进行组分析。我想保持因子的顺序与case_when. 在这种情况下,顺序应该是"Excellent" "Good" "Fail"。我怎样才能做到这一点而不像在levels=c('Excellent', 'Good', 'Fail')?
非常感谢。
library(dplyr, warn.conflicts = FALSE)
set.seed(1234)
score <- runif(100, min = 0, max = 100)
Performance <- function(x) {
case_when(
is.na(x) ~ NA_character_,
x > 80 ~ 'Excellent',
x > 50 ~ 'Good',
TRUE ~ 'Fail'
) %>% factor(levels=c('Excellent', 'Good', 'Fail'))
}
performance <- Performance(score)
levels(performance)
#> [1] "Excellent" "Good" "Fail"
table(performance)
#> performance
#> Excellent Good Fail
#> 15 30 55
Run Code Online (Sandbox Code Playgroud)
最后,我想出了一个解决方案。对于那些有兴趣的人,这是我的解决方案。我写了一个函数fct_case_when(假装是 中的函数forcats …
假设我有以下类,它有一个方法set_value.哪种实施更好?
class S {
public:
// a set_value method
private:
Some_type value;
};
Run Code Online (Sandbox Code Playgroud)
void S::set_value(Some_type value)
{
this->value = std::move(value);
}
Run Code Online (Sandbox Code Playgroud)
void S::set_value(const Some_type& value)
{
this->value = value;
}
void S::set_value(Some_type&& value)
{
this->value = std::move(value);
}
Run Code Online (Sandbox Code Playgroud)
第一种方法只需要定义一种方法,而第二种方法需要两种方法.
但是,第一种方法似乎效率较低:
而对于第二种方法,仅执行一次分配操作.
那么,哪种实施更好?或者它是否重要?
还有一个问题:以下代码是否等同于第二种方法中的两个重载方法?
template <class T>
void S::set_value(T&& value)
{
this->value = std::forward<T>(value);
}
Run Code Online (Sandbox Code Playgroud) 根据cppreference,std::array构造函数在std::array创建时执行默认初始化.但是,当我在Visual Studio 12.0中进行一些测试时,在某些情况下std::array似乎正在执行值初始化.
std::array<int, 3> arr1; // gives me some garbage values, as expected
auto arr2 = std::array<int, 3>(); // gives me three 0, value-initialize?
Run Code Online (Sandbox Code Playgroud)
此外,当它std::array是类的成员时,有时它具有不确定的值,而有时它全部为零.
class Container {
public:
Container() ...
int& operator[](size_t i) { return arr[i]; }
size_t size() { return ARR_SIZE; }
private:
static const size_t ARR_SIZE = 3;
std::array<int, ARR_SIZE> arr;
};
Run Code Online (Sandbox Code Playgroud)
如果构造函数未显式定义或arr不在成员初始arr值设定项列表中,则包含不确定的值.
Container() {} // arr has indeterminate values, same for …Run Code Online (Sandbox Code Playgroud)