小编Den*_* YL的帖子

R:转换为与 case_when 相同的级别顺序的因子

在进行数据分析时,有时需要将值重新编码为因子以进行组分析。我想保持因子的顺序与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 …

r data-analysis dplyr tidyverse forcats

12
推荐指数
1
解决办法
3710
查看次数

通过值和移动,或两种方法

假设我有以下类,它有一个方法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)

第一种方法只需要定义一种方法,而第二种方法需要两种方法.

但是,第一种方法似乎效率较低:

  1. 根据传递的参数复制/移动参数的构造函数
  2. 移动作业
  3. 参数的析构函数

而对于第二种方法,仅执行一次分配操作.

  1. 复制/移动分配取决于调用哪个重载方法

那么,哪种实施更好?或者它是否重要?

还有一个问题:以下代码是否等同于第二种方法中的两个重载方法?

template <class T>
void S::set_value(T&& value)
{
  this->value = std::forward<T>(value);
}
Run Code Online (Sandbox Code Playgroud)

c++ move-semantics perfect-forwarding c++11

5
推荐指数
1
解决办法
562
查看次数

std :: array是default-initialize还是value-initialize?

根据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)

c++ arrays visual-studio c++11

4
推荐指数
1
解决办法
2529
查看次数