小编cdm*_*hai的帖子

R:在向空数据帧添加行时丢失列名

我刚刚开始使用R并遇到一个奇怪的行为:当在空数据框中插入第一行时,原始列名称会丢失.

例:

a<-data.frame(one = numeric(0), two = numeric(0))
a
#[1] one two
#<0 rows> (or 0-length row.names)
names(a)
#[1] "one" "two"
a<-rbind(a, c(5,6))
a
#  X5 X6
#1  5  6
names(a)
#[1] "X5" "X6"
Run Code Online (Sandbox Code Playgroud)

如您所见,列名12X5X6替换.

有人可以告诉我为什么会这样,并且有没有正确的方法来做到这一点而不会丢失列名?

霰弹枪解决方案是将名称保存在辅助矢量中,然后在完成数据帧处理后将其添加回来.

谢谢

语境:

我创建了一个函数,它收集一些数据并将它们作为新行添加到作为参数接收的数据帧中.我创建数据框,遍历我的数据源,将data.frame传递给每个函数调用以填充其结果.

r names dataframe rbind

62
推荐指数
4
解决办法
3万
查看次数

Java ConcurrentHashMap原子获取(如果存在)

如何在并发哈希映射上执行安全获取操作?(与putIfAbsent相同)

不好的例子,不是非常线程安全(检查然后行为情况):

ConcurrentMap<String, SomeObject> concMap = new ...

//... many putIfAbsent and remove operations

public boolean setOption(String id, Object option){
   SomeObject obj = concMap.get(id);

   if (obj != null){
      //what if this key has been removed from the map?
      obj.setOption(option);
      return true;
   }

   // in the meantime a putIfAbsent may have been called on the map and then this
   //setOption call is no longer correct

   return false;
}
Run Code Online (Sandbox Code Playgroud)

另一个糟糕的例子是:

   public boolean setOption(String id, Object option){
       if (concMap.contains(id)){
           concMap.get(id).setOption(option);
           return true;
       } …
Run Code Online (Sandbox Code Playgroud)

java concurrenthashmap

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

如何在Powershell中分配和引用包含方括号的环境变量

未指定PSDrive时,以下工作:

${[foo]}="bar"
echo ${[foo]}
Run Code Online (Sandbox Code Playgroud)

但是以下方法不起作用

$env:${[foo]}="bar"
At line:1 char:1 
+ $env:${[foo]}="bar"
+ ~~~~~
Variable reference is not valid. ':' was not followed by a valid variable name character. Consider using ${} to delimit the name.
At line:1 char:6
+ $env:${[foo]}="bar"
+      ~~~~~~~~~~~~~~
Unexpected token '${[foo]}="bar"' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : InvalidVariableReferenceWithDrive
Run Code Online (Sandbox Code Playgroud)
${env:[foo]}="bar"
Cannot find path 'env:[foo]' because it does not exist. 
At line:1 char:1
+ ${env:[foo]}="bar"
+ ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : …
Run Code Online (Sandbox Code Playgroud)

syntax powershell namespaces environment-variables

2
推荐指数
1
解决办法
196
查看次数